Skip to content

ClientServer Validation

World Wide Web Server edited this page Jul 4, 2012 · 13 revisions

Implementing client-side and server-side validation usually requires a significant duplication of effort. Despite following the same logic rules, the code usually must be developed in two different environments - e.g. javascript and php.

For those who are too lazy to do the same work twice (like I am), here is a crude prototype of a validation library (subclass of built-in Validation class) that would do this work for you.

The usage is simple:

  1. Add a method to your controller, where you set up your validation rules.
  2. Call this method twice per form life-cycle: once before rendering the form (html), and again after it has been submitted.

For example:

  1. Set up validation: [code] function _setup_validation() { $this->load->library('validation');

     $fields = array(
         'email'=>'Email',
         'password'=>'Password',
         'password2'=>'Confirm Password',
         'firstname' => 'First Name',
         'lastname' => 'Last Name',
         'address1'=>'Address 1',
         'city'=>'City',
         'zipcode'=>'Zip'
     );
     
     $rules = array(
         'email'=>'required|valid_email',
         'password'=>'min_length[5]',
         'password2'=>'required|matches[password]',
         'firstname' => 'required',
         'lastname' => 'required',
         'address1'=>'required',
         'city'=>'min_length[2]',
         'zipcode'=>'exact_length[5]'
     );
     
     $this->validation->set_fields($fields);
     $this->validation->set_rules($rules);
    

    } [/code]

  2. When rendering the form, define your validation rules and then call special function from our Validation (sub)class to generate a corresponding [removed]

[code] function index() { $this->_setup_validation();

    $data['javascript'] = $this->validation->javascript();
    $this->load->view('register', $data);
}

[/code]

  1. In your view, use 'javascript' variable to inject the contents of our validation (js) script:

[code] <html> <head> <title>Account Registration</title> <?= @$javascript ?> </head> ... [/code]

  1. Once the form has been submitted, process it as usual:

[code] function submit() { $this->_setup_validation();

    if ($this->validation->run() == false)
        return $this->index();

    $this->load->view('sucess');
}

[/code]

Clone this wiki locally