Monday, November 11, 2013

Client + Server Side Validation = New Love

Having to do some recent form validation I wanted to have a solution that worked both on the client and server side. I found it!

It comes from combining jQuery Validation Plugin and jQuery Validation PHP Plugin

Using both of these libraries I create one rule file and incorporate it for both client and server side validation. My recent rule file looks like the following.

<?php
    $validation_rules = array(
        'rules' => array(
            'timestamp' => array(
                'required' => true,
                'number' => true
            ),
            'full-name' => 'required',
            'address' => 'required',
            'city-state-zip' => 'required',
            'home-phone' => 'required',
            'email' => array(
                'required' => true,
                'email' => true
            ),
            'birthday' => array(
                'required' => true,
                'dateUS' => true
            )    
        ),
        'messages' => array(
            'timestamp' => array(
                'required' => 'Select a date.',
                'number' => 'The date selected is not valid.'
             ),
            'full-name' => 'Enter your full name.',
            'address' => 'Enter your address.',
            'city-state-zip' => 'Enter your city state and zip.',
            'home-phone' => 'Enter a phone number.',    
            'email' => array(
                'required' => 'Enter your email address',
                'email' => 'Enter a valid email address'
            ),
            'birthday' => array(
                'required' => 'Enter your birthday',
                'dateUS' => 'Enter a date in the format mm/dd/yyyy.' 
            )
        )
    );
?> 

Notice how I have dateUS. That is a custom validation rule I set up. Adding custom rules is really easy for both libraries.

I am using Twitter Bootstrap for my framework, and the following js helps jQuery validator work great on the client side.

var settings = $('#form').validate(<?php echo json_encode($validation_rules); ?>).settings;
$.extend(settings, {
    errorClass: 'help-block',
    highlight: function(element){
        $(element).closest('.control-group').addClass('error');
    },
    success: function(element){
        element.closest('.control-group').removeClass('error');
    }
});

My post to page now follows something along the following logic.

<?php 
    require_once 'rules.php'; 
    require_once 'validator.class.php'; 

    $oValidator = new Validator($validation_rules);

    $validated_data = $oValidator->validate($_POST);

    if (count($validated_data) == 0){
        echo 'no errors';
    }
    else{
        print_r($validated_data);
    }
?>

Saturday, October 13, 2012

PHP Access Specifiers

There are three access specifiers in PHP: public, private, and protected.

Public

The access specifier public allows properties of a class to be accessed/modified outside the class without having to go through a get or set method. This allows for the least amount of protection for the property.

class Person {
 public $name;
 
 public function setName($name) {
  $this->name = $name;
 }
 
 public function getName() {
  return $this->name;
 }
}
 
$p = new Person();
$p->setName("Bob Jones");
echo $p->name;  // echos Bob Jones no error because it is public
$p->name = "Joe Smith" ; // this sets the name to Joe Smith only because it is public

Private

Private is another access specifier that offers the most protection for a property. The property is only editable within the class itself.

class Person {
 private $name;
 
 public function setName($name) {
  $this->name = $name;
 }
 
 public function getName() {
  return $this->name;
 }
}
 
$p = new Person();
$p->setName("Bob Jones");
echo $p->getName(); //this will echo Bob Jones
echo $p->name; //can't access name this way, only through getName()
$p->name = "Joe Smith" ; //can't set name this way either         

Protected

The protected access specifier offers more protection then public but allows for a property to be accessed in its class and all other classes that extend its class.

class Person {
 protected $name;
 
 public function setName($name) {
  $this->name = $name;
 }
 
 public function getName() {
  return $this->name;
 }
}
 
class Employee extends Person {
 
 private $employeeNumber;
 
 public function setEmployee($name, $employeeNumber) {
  $this->name = $name; //this is storing name in the person class 
  $this->employeeNumber = $employeeNumber;
 }
        
}
 
$e = new Employee();
$e->setEmployee("Bob Jone",10000100);
echo $e->name; // this would throw an error as it is only accessable through methods in Employee or Person class

Monday, August 6, 2012

Adding Time

Today I thought I would add a quick note about how to utilize the strtotime() function in PHP to add time and still keep it in the desired format. The trick is to pass the strtotime() function to the date() function in order to keep the formatting.

$end_time = date('H:i:s', strtotime($start_time)+5);
// 5 represents time to be added in seconds. 

Tuesday, June 19, 2012

Writing Classes with PHP

Classes allow for the creation of objects that can contain multiple properties. The properties can then be pulled from the class using methods for a specific object. I recently wanted to create an array of objects, so I created an index.php page that looked similar to this.

<?php
include("class_lib.php");

for ($i=0; $i < 10; $i++){
// Use data pulled from a database or post data
   $array[$i] = new person ($name,$age,$address);
}
var_dump($array);
?>

I first include the class I am going to use to create the objects and then I create a new person for each instance of the array. I suggested that you get the data from post data or from a database.

The class will then look something like this.

<?php
class person{
  private $name;
  private $age;
  private $address;
  public function __construct($persons_name, $persons_age, $persons_address){
     $this->name = $persons_name;
     $this->age = $persons_age;
     $this->address = $persons_address;
  }

  // You can create set methods like

  public function set_name($new_name) {
     $this->name = $new_name;
  }

  //Or you can create get mehthods like

  public function get_name(){
     return $this->name;
  }

}
?>

If you still have questions, then a good resource is to go to killerphp.com

Tuesday, June 12, 2012

Error Reporting with PHP

I often find myself needing to display the errors and warnings for my php scripts. A quick and easy way of doing this is adding the following lines of code to the top of your php page.

error_reporting(E_ALL);
ini_set('display_errors', '1');