How to validate form in codeigniter framewok?

form validation in codeigniter

In Codeigniter, For form validation we use form_validation library. you can use this library anywhere in your controller class.

In Controller file we have create a class named "validate-form" where index() function initializes "form_validation" library :

function index()
{
//including validation library
$this->load->library('form_validation');
}

OR

and you can also set Autoload library(autoload.php).
$autoload['libraries'] = array('database', 'pagination', 'session', 'form_validation');

To set validation rules we will use the set_rules() function

$this->form_validation->set_rules();

set_rules() method takes three parameters :

  • 1. Actual field name (e.g. uname).
  • 2. Name of the field used to identify it (e.g. Username).
  • 3. Validation rules for the form field.
  • $this->form_validation->set_rules('uname', 'Username', 'required');


    The third parameter can be set for multiple rules like this :

    $this->form_validation->set_rules('uname', 'Username', 'required|min_length[4]|max_length[10]);

    set_rules() method is used to define the validation rules for the form fields.
    $this->form_validation->run() return Boolean value, TRUE on success and FALSE on failure.


    list of the rules with their specification :

    required // Returns FALSE if the form field is empty.

    matches // Returns FALSE if the form field does not match the defined value of parameter.

    is_unique // Returns FALSE if the form field is not unique to the table and field name in the parameter.

    min_length // Returns FALSE if the form field is shorter than the parameter value.

    max_length // Returns FALSE if the form field is longer than the parameter value.

    exact_length // Returns FALSE if the form field is not exactly the parameter value.

    greater_than // Returns FALSE if the form field is less than the parameter value or not numeric.

    less_than // Returns FALSE if the form field is greater than the parameter value or not numeric.

    alpha // Returns FALSE if the form field contains anything other than alphabetical characters.

    alpha_numeric // Returns FALSE if the form field contains anything other than alpha-numeric characters.

    alpha_dash // Returns FALSE if the field contains anything other than alpha-numeric characters, underscores or dashes.

    numeric // Returns FALSE if the form field contains anything other than numeric characters.

    integer // Returns FALSE if the form field contains anything other than an integer.

    decimal // Returns FALSE if the form field contains anything other than a decimal number.

    is_natural // Returns FALSE if the form field contains anything other than a natural number.

    is_natural_no_zero // Returns FALSE if the form field contains anything other than a natural number, but not zero.

    valid_email // Returns FALSE if the form field does not contain a valid email address.

    valid_emails // Returns FALSE if any value provided in a comma separated list is not a valid email.

    valid_ip // Returns FALSE if the supplied IP is not valid.

    valid_base64 // Returns FALSE if the supplied string contains anything other than valid Base64 characters.

    VIEW FILE: valform.php

    <!DOCTYPE html>
    <html>
    <head>
    <title>Validating Form Fields Using CodeIgniter</title>
    <link href='http://fonts.googleapis.com/css?family=Marcellus' rel='stylesheet' type='text/css'>
    <link href="http://localhost/CodeIgniter/css/styles.css" rel="stylesheet" type="text/css">
    </head>
    <body>
    <div id="container">
    <?php echo form_open('validate_ctrl'); ?>
    <h1>Validating form fields using CodeIgniter</h1>
    <?php echo form_label('Student Name :'); ?><?php echo form_error('dname'); ?>
    <?php echo form_input(array('id' => 'dname', 'name' => 'dname')); ?>
    <?php echo form_label('Student Email :'); ?> <?php echo form_error('demail'); ?>
    <?php echo form_input(array('id' => 'demail', 'name' => 'demail')); ?>
    <?php echo form_label('Student Mobile No. :'); ?> <?php echo form_error('dmobile'); ?>
    <?php echo form_input(array('id' => 'dmobile', 'name' => 'dmobile','placeholder'=>'10 Digit Mobile No.')); ?>
    <?php echo form_label('Student Address :'); ?> <?php echo form_error('daddress'); ?>
    <?php echo form_input(array('id' => 'daddress', 'name' => 'daddress')); ?>
    <?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?> <?php echo form_close(); ?>
    </div>
    </body>
    </html>

    CONTROLLER FILE: validate_ctrl.php

    <?php
    class validate_ctrl extends CI_Controller {
    function __construct() {
    parent::__construct();
    $this->load->model('form_model');
    }
    function index()
    {
    // Including Validation Library
    $this->load->library('form_validation');
    // Displaying Errors In Div
    $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
    // Validation For Name Field
    $this->form_validation->set_rules('dname', 'Username', 'required|min_length[5]|max_length[15]');
    // Validation For Email Field
    $this->form_validation->set_rules('demail', 'Email', 'required|valid_email');
    // Validation For Contact Field
    $this->form_validation->set_rules('dmobile', 'Contact No.', 'required|regex_match[/^[0-9]{10}$/]');
    // Validation For Address Field
    $this->form_validation->set_rules('daddress', 'Address', 'required|min_length[10]|max_length[50]');
    if ($this->form_validation->run() == FALSE)
    {
    $this->load->view('valform');
    }
    else
    {
    $this->load->view('formsubmit');
    }
    }
    }
    ?>

    CSS FILE: styles.css

    #container {
    width:960px;
    height:610px;
    margin:50px auto
    }
    .error {
    color:red;
    font-size:13px;
    margin-bottom:-15px
    }
    form {
    width:320px;
    padding:0 50px 20px;
    background:linear-gradient(#fff,#CBCE80);
    border:1px solid #ccc;
    box-shadow:0 0 5px;
    font-family:'Marcellus',serif;
    float:left;
    margin-top:10px
    }
    h1 {
    text-align:center;
    font-size:28px
    }
    hr {
    border:0;
    border-bottom:1.5px solid #ccc;
    margin-top:-10px;
    margin-bottom:30px
    }
    label {
    font-size:17px
    }
    input {
    width:100%;
    padding:10px;
    margin:6px 0 20px;
    border:none;
    box-shadow:0 0 5px
    }
    input#submit {
    margin-top:20px;
    font-size:18px;
    background:linear-gradient(#22abe9 5%,#36caf0 100%);
    border:1px solid #0F799E;
    color:#fff;
    font-weight:700;
    cursor:pointer;
    text-shadow:0 1px 0 #13506D
    }
    input#submit:hover {
    background:linear-gradient(#36caf0 5%,#22abe9 100%)
    }


    how to use xss_clean form validation.

    load security Helper on autoload.php

    $autoload['helper'] = array('security');
    No need to do anything more.

    xss_clean is no longer part of form validation in Codeingitore 3
    Just remove xss_clean from your validation roul

    $this->form_validation->set_rules('pword', 'Password', 'required|max_length[30]|callback_pword_check');
    If you really, really need to apply that rule, you should now also load the Security Helper, which contains xss_clean() as a regular function and therefore can be also used as a validation rule.

    go to application/config/autoload.php :

    $autoload['helper'] = array('security');
    Or, before your form validation

    $this->load->helper('security');

    xss_clean is no longer part of form validation.

    Unable to access an error message corresponding to your field name Username.(xss_clean)

    The alternative is not to use it, as xss_clean is doing sanitization and not validation. xss_clean is part of security helper. If you need to do it, after validation you do.

    $this->load->helper('security'); `
    $value = $this->input->post('email',TRUE); //where TRUE enables the xss filtering
    Also, you can enable global xss filtering in the config.php file

    $config['global_xss_filtering'] = TRUE;


    Example :-

    File name : Home.php

    class Home extends CI_Controller {

    public function __construct() {
    parent::__construct();
    $this->load->library(array('form_validation','session')); // load form lidation libaray & session library
    $this->load->helper(array('url','html','form')); // load url,html,form helpers optional
    }

    public function index(){

    // set validation rules
    $this->form_validation->set_rules('name', 'Name', 'required|min_length[4]|max_length[10]');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    $this->form_validation->set_rules('number', 'Phone Number', 'required|numeric|max_length[15]');
    $this->form_validation->set_rules('subject', 'Subject', 'required|max_length[10]|alpha');
    $this->form_validation->set_rules('message', 'Message', 'required|min_length[12]|max_length[100]');


    // hold error messages in div
    $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

    // check for validation
    if ($this->form_validation->run() == FALSE) {
    $this->load->view('form_validation_demo');
    }else{
    $this->session->set_flashdata('item', 'form submitted successfully');
    redirect(current_url());
    }

    }
    }

    view :- form_validation_demo.php

    <?php if(validation_errors()) { ?>
    <div class="alert alert-warning">
    <?php echo validation_errors(); ?>
    </div>
    <?php } ?>


    <?php if($this->session->flashdata('item')) { ?>
    <div class="alert alert-success">
    <?php echo $this->session->flashdata('item'); ?>
    </div>
    <?php } ?>


    <?php echo form_open(); ?>

    <div class="form-group">
    <?php echo form_label('Your Name','name'); ?>
    <?php echo form_input(array("class"=>"form-control","name" => "name", "placeholder"=>"Enter Name","value" => set_value('name'))); ?>
    </div>

    <div class="form-group">
    <?php echo form_label('Email address','EmailAddress'); ?>
    <?php echo form_input(array("class"=>"form-control","name" => "email", "placeholder"=>"Enter email","value" => set_value('email'))); ?>
    </div>

    <div class="form-group">
    <?php echo form_label('Phone Number','number'); ?>
    <?php echo form_input(array("class"=>"form-control","name" => "number", "placeholder"=>"Enter Phone Number","value" => set_value('number'))); ?>
    </div>

    <div class="form-group">
    <?php echo form_label('Subject','subject'); ?>
    <?php echo form_input(array("class"=>"form-control","name" => "subject", "placeholder"=>"Enter Subject","value" => set_value('subject'))); ?>
    </div>

    <div class="form-group">
    <?php echo form_label('Message','message'); ?>
    <?php echo form_input(array("class"=>"form-control","name" => "message", "placeholder"=>"Enter Message","value" => set_value('message'))); ?>
    </div>

    <button type="submit" class="btn btn-default">Submit</button>
    <?php echo form_close(); ?>





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here