Validation in CodeIgniter is simple and easy to used. we will use form_validation library in CodeIgniter for form validation and return error on form submit.
$this->load->library('form_validation');
Following are default validation rules of CodeIgniter:
1) required
2) matches
3) regex_match
4) differs
5) is_unique
6) min_length
7) max_length
8) exact_length
9) greater_than
10) greater_than_equal_to
11) less_than
12) less_than_equal_to
13) in_list
14) alpha
15) alpha_numeric
16) alpha_numeric_spaces
17) alpha_dash
18) numeric
19) integer
20) decimal
21) is_natural
22) is_natural_no_zero
23) valid_url
24) valid_email
25) valid_emails
26) valid_ip
27) valid_base64
Now we will check CodeIgniter form validation for simple registration form.
Let’s create simple form having name, email, password, address fields:
<html> <head> <title>Form Validation</title> </head> <body> <?php echo validation_errors(); ?> <?php echo form_open('form'); ?> <h4>Name</h4> <input type="text" name="name" value="<?php echo set_value('name'); ?>" size="50" /> <h4>Email</h4> <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> <h4>Password</h4> <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> <h4>Password Confirm</h4> <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> <div><input type="submit" value="Submit" /></div> </form> </body> </html>
function set_value() return all values. If validation gives error, validation_errors() function return errors.
<?php echo validation_errors(); ?>
Setting Validation Rules :
We are using various rules like required,valid_email, matches[password].
As per requirement we pass multiple parameter in validation its simple and easy
$this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
Check CodeIgniter controller example :
<?php class registration extends CI_Controller { public function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); if ($this->form_validation->run() == FALSE){ $this->load->view('registration_page'); }else{ $this->load->view('registration_success'); } } } ?>