-
Notifications
You must be signed in to change notification settings - Fork 26
ClientServer Validation
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:
- Add a method to your controller, where you set up your validation rules.
- Call this method twice per form life-cycle: once before rendering the form (html), and again after it has been submitted.
For example:
-
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]
-
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]
- 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]
- 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]