Form Validation in CodeIgniter
A form is displayed to the user, who then fills it in and submits it. The Form Validation Library then checks the form against any rules that the developer has set. If an error occurs the library returns these errors and they are shown against the form with the fields re-populated. This process proceeds until a valid form is submitted.
The development process
You create a form, along with a dynamic value from a form helper function—this will re-populate the data if needed. You will also display individual or global errors in the form view file. You set validation rules, which must be adhered to. Then you check to see if the validation process has been run, and if it has not, you load the form view file.
Loading the assets
We need to load one libraries for form validation: the Form Validation Library. We can do this in one line
1 |
$this->load->library('form_validation'); |
Setting the rules
The next step in using the Form Validation Library is to set the rules for the form. These rules are set and must be adhered to. The way we set rules is by using the
set_rules() function of the Form Validation Library. We use the function
as follows:
1 |
$this->form_validation->set_rules('field_name', 'human_name', 'rules'); |
As you can see, the function accepts three parameters. The first is the name of the form field that you wish to set the rule for. The second parameter is the name that you wish to be assigned to this, for humans to read. The final parameter is where you pass any validation rules.
List of validation rules
The following rules are readily available for use:
- required
- matches[field_name]
- min_length[x]
- max_length[x]
- exact_length[x]
- alpha
- alpha_numeric
- alpha_dash
- numeric
- integer
- is_natural
- is_unique
- is_natural_no_zero
- valid_email
- valid_emails
- valid_ip
- valid_base64
The following is a list of all the native rules that are available to use:
Rule | Parameter | Description | Example |
---|---|---|---|
required | No | Returns FALSE if the form element is empty. | |
matches | Yes | Returns FALSE if the form element does not match the one in the parameter. | matches[form_item] |
regex_match | Yes | Returns FALSE if the form element does not match the regular expression. | regex_match[/regex/] |
differs | Yes | Returns FALSE if the form element does not differ from the one in the parameter. | differs[form_item] |
is_unique | Yes | Returns FALSE if the form element is not unique to the table and field name in the parameter. Note: This rule requires Query Builder to be enabled in order to work. | is_unique[table.field] |
min_length | Yes | Returns FALSE if the form element is shorter than the parameter value. | min_length[3] |
max_length | Yes | Returns FALSE if the form element is longer than the parameter value. | max_length[12] |
exact_length | Yes | Returns FALSE if the form element is not exactly the parameter value. | exact_length[8] |
greater_than | Yes | Returns FALSE if the form element is less than or equal to the parameter value or not numeric. | greater_than[8] |
greater_than_equal_to | Yes | Returns FALSE if the form element is less than the parameter value, or not numeric. | greater_than_equal_to[8] |
less_than | Yes | Returns FALSE if the form element is greater than or equal to the parameter value or not numeric. | less_than[8] |
less_than_equal_to | Yes | Returns FALSE if the form element is greater than the parameter value, or not numeric. | less_than_equal_to[8] |
in_list | Yes | Returns FALSE if the form element is not within a predetermined list. | in_list[red,blue,green] |
alpha | No | Returns FALSE if the form element contains anything other than alphabetical characters. | |
alpha_numeric | No | Returns FALSE if the form element contains anything other than alpha-numeric characters. | |
alpha_numeric_spaces | No | Returns FALSE if the form element contains anything other than alpha-numeric characters or spaces. Should be used after trim to avoid spaces at the beginning or end. | |
alpha_dash | No | Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes. | |
numeric | No | Returns FALSE if the form element contains anything other than numeric characters. | |
integer | No | Returns FALSE if the form element contains anything other than an integer. | |
decimal | No | Returns FALSE if the form element contains anything other than a decimal number. | |
is_natural | No | Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc. | |
is_natural_no_zero | No | Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc. | |
valid_url | No | Returns FALSE if the form element does not contain a valid URL. | |
valid_email | No | Returns FALSE if the form element does not contain a valid email address. | |
valid_emails | No | Returns FALSE if any value provided in a comma separated list is not a valid email. | |
valid_ip | Yes | Returns FALSE if the supplied IP address is not valid. Accepts an optional parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format. | |
valid_base64 | No | Returns FALSE if the supplied string contains anything other than valid Base64 characters. |
Source : https://www.codeigniter.com/userguide3/libraries/form_validation.html
As you can see, some of these rules have a single parameter.
The rule matches[]
will return TRUE if the field matches the field name passed to it.
The min_length[]
, max_length[]
, and exact_length[]
rules will take an integer as a parameter and check if the minimum length, maximum length respectively, or exact length matches the rule.
The rules with no parameters are pretty much self-explanatory. You are able to use more than one rule, simply separate rules with a vertical bar ‘|’ and they will cascade.
The rules
Now that we know how to set rules and what the rules we can use are, we can go ahead and set the rules necessary for our form. All fields should be required, and the e-mail field should be validated to ensure that the e-mail address is correctly formatted.
1 2 3 4 5 6 7 8 9 |
$this->form_validation-> set_rules('fullname', 'Full Name', 'required|alpha'); $this->form_validation-> set_rules('email', 'Email Address', 'required|valid_email'); $this->form_validation-> set_rules('phonenumber', 'Phone Number', 'required|numeric|exact_length[10]'); $this->form_validation-> set_rules('username', 'User Name', 'required|alpha_numeric|min_length[6]|min_length[12]'); |
Check the validation process
Instead of checking one of the form field’s POST value to check if the form has been submitted, we simply check to see if the Form Validation Library has run. We do this by using the following code:
1 2 3 4 5 6 7 8 |
if($this->form_validation->run()) { // get the post values } else { //load the form } |
Example 1
Create a view signup_form view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- This file has been downloaded from Bootsnipp.com. Enjoy! --> <title>CodeIgniter Form Validation Tutorial</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <section id="login"> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="form-wrap"> <h1>Signup Form</h1> <?php echo form_open('signupform',['name'=>'signup']);?> <?php echo validation_errors('<div style="color:red">', '</div>'); ?> <div class="form-group"> <?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter your full name','class'=>'form-control']);?> </div> <div class="form-group"> <?php echo form_input(['name'=>'email','id'=>'email','placeholder'=>'Enter your valid email','class'=>'form-control']);?> </div> <div class="form-group"> <?php echo form_input(['name'=>'phonenumber','id'=>'phonenumber','placeholder'=>'Enter your 10 digit mobile number','class'=>'form-control']);?> </div> <div class="form-group"> <?php echo form_input(['name'=>'username','id'=>'username','placeholder'=>'Enter your username','class'=>'form-control']);?> </div> <div class="form-group"> <?php echo form_password(['name'=>'password','id'=>'password','placeholder'=>'Enter your password','class'=>'form-control']);?> </div> <div class="form-group"> <?php echo form_password(['name'=>'cpassword','id'=>'cpassword','placeholder'=>'Confirm your password','class'=>'form-control']);?> </div> <div class="form-group"> <?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'10','id'=>'address','class'=>'form-control','placeholder'=>'Enter your address']);?> </div> <?php echo form_submit(['name'=>'submit','value'=>'Submit','class'=>'btn btn-custom btn-lg btn-block']);?> <?php echo form_close();?> </div> </div> <!-- /.col-xs-12 --> </div> <!-- /.row --> </div> <!-- /.container --> </section> </body> </html> |
Create signupform controller and don’t forget to load form_validation library
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php class Signupform extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('form_validation'); } public function index(){ $this->form_validation->set_rules('fullname','Full Name','required|alpha'); $this->form_validation->set_rules('email','Email id','required|valid_email'); $this->form_validation->set_rules('phonenumber','Phone Number','required|numeric|exact_length[10]'); $this->form_validation-> set_rules('username','User name','required|alpha_numeric|min_length[6]|max_length[12]|is_unique[tblusers.username]'); $this->form_validation->set_rules('password','Password','required|min_length[6]'); $this->form_validation->set_rules('cpassword','Confirm Password','required|min_length[6]|matches[password]'); if($this->form_validation->run()){ echo "Form submitted"; } else{ $this->load->view("signup_form"); } } } |
This method will show all errors at one place like this :
If you want to print an error below partcular field then use form_error function.
1 |
<?php echo form_error('field name', '<div class="error">', '</div>'); ?> |
Ex2 :
Signup_form view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- This file has been downloaded from Bootsnipp.com. Enjoy! --> <title>CodeIgniter Form Validation Tutorial</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <section id="login"> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="form-wrap"> <h1>Signup Form</h1> <?php echo form_open('signupform',['name'=>'signup']);?> <div class="form-group"> <?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter your full name','class'=>'form-control']);?> <?php echo form_error('fullname','<div style="color:red">', '</div>'); ?> </div> <div class="form-group"> <?php echo form_input(['name'=>'email','id'=>'email','placeholder'=>'Enter your valid email','class'=>'form-control']);?> <?php echo form_error('email','<div style="color:red">', '</div>'); ?> </div> <div class="form-group"> <?php echo form_input(['name'=>'phonenumber','id'=>'phonenumber','placeholder'=>'Enter your 10 digit mobile number','class'=>'form-control']);?> <?php echo form_error('phonenumber','<div style="color:red">', '</div>'); ?> </div> <div class="form-group"> <?php echo form_input(['name'=>'username','id'=>'username','placeholder'=>'Enter your username','class'=>'form-control']);?> <?php echo form_error('username','<div style="color:red">', '</div>'); ?> </div> <div class="form-group"> <?php echo form_password(['name'=>'password','id'=>'password','placeholder'=>'Enter your password','class'=>'form-control']);?> <?php echo form_error('password','<div style="color:red">', '</div>'); ?> </div> <div class="form-group"> <?php echo form_password(['name'=>'cpassword','id'=>'cpassword','placeholder'=>'Confirm your password','class'=>'form-control']);?> <?php echo form_error('cpassword','<div style="color:red">', '</div>'); ?> </div> <div class="form-group"> <?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'10','id'=>'address','class'=>'form-control','placeholder'=>'Enter your address']);?> </div> <?php echo form_submit(['name'=>'submit','value'=>'Submit','class'=>'btn btn-custom btn-lg btn-block']);?> <?php echo form_close();?> </div> </div> <!-- /.col-xs-12 --> </div> <!-- /.row --> </div> <!-- /.container --> </section> </body> </html> |
Controller will be the same for both methods.
Output for Ex2 will be like this: