PHPGurukul

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

$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:

$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
RuleParameterDescriptionExample
requiredNoReturns FALSE if the form element is empty.
matchesYesReturns FALSE if the form element does not match the one in the parameter.matches[form_item]
is_uniqueYesReturns FALSE if the form element is not unique to the table and field name in the parameter.is_unique[table.field]
min_lengthYesReturns FALSE if the form element is shorter then the parameter value.min_length[6]
max_lengthYesReturns FALSE if the form element is longer then the parameter value.max_length[12]
exact_lengthYesReturns FALSE if the form element is not exactly the parameter value.exact_length[8]
greater_thanYesReturns FALSE if the form element is less than the parameter value or not numeric.greater_than[8]
less_thanYesReturns FALSE if the form element is greater than the parameter value or not numeric.less_than[8]
alphaNoReturns FALSE if the form element contains anything other than alphabetical characters.
alpha_numericNoReturns FALSE if the form element contains anything other than alpha-numeric characters.
alpha_dashNoReturns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.
numericNoReturns FALSE if the form element contains anything other than numeric characters.
integerNoReturns FALSE if the form element contains anything other than an integer.
decimalNoReturns FALSE if the form element contains anything other than a decimal number.
is_naturalNoReturns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.
is_natural_no_zeroNoReturns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
valid_emailNoReturns FALSE if the form element does not contain a valid email address.
valid_emailsNoReturns FALSE if any value provided in a comma separated list is not a valid email.
valid_ipNoReturns FALSE if the supplied IP is not valid. Accepts an optional parameter of “IPv4” or “IPv6” to specify an IP format.
valid_base64NoReturns 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.

$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:

if($this->form_validation->run())
{
// get the post values
}
else
{
//load the form
}

Example 1
Create a view signup_form view

<!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

<?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 :
Form Validation Error1
If you want to print an error below partcular field then use form_error function.

<?php echo form_error('field name', '<div class="error">', '</div>'); ?>

Ex2 :
Signup_form view

<!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:
Form Validation Error2
View Demo 1 View Demo 2

CI Form Validation (Download script 1)
Size: 2.61 MB
Version: V 1.0

CI Form Validation (Download script 2)
Size: 2.61 MB
Version: V 1.)

Anuj Kumar

This is Anuj Kumar. I’m a professional web developer with 4+ year experience. I write blogs in my free time. I love to learn new technologies and share with others.
I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials.
.

Recommended Tutorials for you


3 comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.