• logo
  • PHP
  • PHP OOPs
  • script
    • JavaScript
    • JQuery
    • Ajax
    • AngularJs
    • VueJs
    • NodeJs
    • ReactJs
  • wordpress
  • Codeigniter
  • Codeigniter 4
  • Laravel
  • Python
  • MySql
  • Json
  • C
  • C++
  • More ...
    • Cakephp Framework
    • MongoDb
    • MySqli PDO
    • .htaccess
    • HTML 5
    • CSS
    • SEO
    • DCA

Codeigniter Tutorials

  • What is codeigniter?
  • Application_Architecture
  • MVC Architecture
  • HMVC Architecture
  • Codeigniter Configuration
  • Remove index.php from url in codeigniter
  • MVC Concept
  • View
  • Alternate PHP Syntax for View Files
  • Routing
  • Codeigniter URL
  • Get Current URL
  • Previous page URL get
  • Seo Friendly URL
  • Slug Create in codeigniter
  • What is _remap() function
  • Remove controller name from url in codeigniter
  • Codeigniter Controller Class
  • Class Constructor
  • GET $ POST method in Codeigniter
  • Models
  • Basepath, Apppath, FCPATH
  • URI Segment
  • Page Redirect
  • Helper class
  • Custom Helper class
  • Form Helper
  • Common Helper Functions
  • Common Function
  • Array Problems
  • Call controller in Helper
  • Add active class to menu using Helper class
  • Custom Library
  • Custom Library Example
  • when to use get_instance()
  • Codeigniter Hook
  • how to work inline css in codeigniter
  • Custom 404 page
  • 404 custom error page
  • Create custom config file in codeigniter
  • How to set and get config item value
  • How to Speed Up CodeIgniter App?
  • Codeigniter Functions
  • Session
  • cookies
  • How to Set & Get Tempdata in Codeigniter
  • flash messages in Codeigniter
  • Flashdata
  • Encryption and Decryption In CodeIgniter
  • Codeigniter security
  • csrf token form security
  • Password Hashing
  • Form Validation
  • Custom Validation
  • Registration Form with validation
  • Server Side Form Validation
  • Validate Select Option Field
  • Date Format Validation
  • Date Format change in codeigniter
  • Date Functions
  • DOB Validation
  • CI CRUD
  • User SignUp
  • User Login
  • User Logout
  • Login Account
  • Login form with RememberMe
  • Login Form with session
  • User change password
  • Change Password with Callback Validation to Check Old Password
  • Forgot password
  • Reset password
  • Insert data in database
  • Fetch data from database
  • Update data in database
  • Delete data in database
  • File Upload
  • Image Upload with resize Image
  • Upload Multiple file and images
  • Upload Multiple images with CRUD
  • File and image update
  • Upload Image Using Ajax.
  • Email Send
  • Email Send Using Email library
  • Email Send Using SMTP Gmail
  • Notification send
  • store data in json format in DB
  • Json parse
  • Fetch data Using Ajax with Json data
  • How to Show data Using Ajax with Json parse
  • Get JSON Data from PHP Script using jQuery Ajax
  • Insert data Using Ajax
  • Submit data Using Ajax with form validation
  • How to show data Using Ajax in codeigniter
  • Insert & Update Using Ajax
  • Registration Form With Validation Using Ajax in codeigniter
  • Delete data Using Ajax Confirmation
  • Delete All data Using checkbox selection
  • Ajax CSRF Token
  • Ajax Post
  • Ajax serverside form validation
  • Contact form using AJAX with form validation
  • DataTable Using Ajax dynamically
  • DataTables pagination using AJAX with Custom filter
  • DataTables AJAX Pagination with Search and Sort in codeigniter
  • DataTables in Codeigniter using Ajax
  • Ajax Custom Serarch
  • Ajax Live Data Search using Jquery PHP MySql
  • Ajax Custom Serarch and sorting in datatable
  • Dynamic Search Using Ajax
  • Autocomplete using jquery ajax
  • Jquery Ajax Autocomplete Search using Typeahead
  • Dynamic Dependent Dropdown Using Ajax
  • Dynamic Dependent Dropdown list Using Ajax
  • Dynamic Dependent Dropdown in codeigniter using Ajax
  • ajax username/email availability check using JQuery
  • Check Email Availability Using Ajax
  • Data Load on mouse scroll
  • Ajax CI Pagination
  • Pagination in codeigniter
  • Ajax Codeigniter Pagination
  • email exists or not using ajax with json
  • CRUD using AJAX With Modal popup in CI
  • Add / Show Data on modal popup using Ajax
  • Modal popup Validation using Ajax
  • Data show on Modal popup Using Ajax
  • Add / Remove text field dynamically using jquery ajax
  • How to Add/Delete Multiple HTML Rows using JavaScript
  • Delete Multiple Rows using Checkbox
  • Multiple Checkbox value
  • Form submit using jquery Example
  • REST & SOAP API
  • Multi-Language implementation in CodeIgniter
  • How to pass multiple array in view
  • Captcha
  • create zip file and download
  • PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
  • data export in excel sheet
  • Excel File generate in Codeigniter using PHPExcel
  • Dompdf library
  • tcpdf library
  • Html table to Excel & docs download
  • CI Database Query
  • Database Query
  • SQL Injection Prevention
  • Auth Model
  • Join Mysql
  • Tree View in dropdown option list
  • OTP Integration in codeigniter
  • curl post
  • download file using curl
  • Sweet Alert
  • Sweet alert Delete & Success
  • Log Message in Codeigniter
  • Menu & Submenu show dynamically
  • Set Default value in input box
  • Cron Jobs
  • Stored Procedure
  • Display Loading Image when AJAX call is in Progress
  • Send SMS
  • IP Address
  • Codeigniter Tutorialspoint
  • Website Link
  • How To Create Dynamic Xml Sitemap In Codeigniter
  • Paypal Payment Integration
  • Get Latitude and Longitude From Address in Codeigniter Using google map API
  • How To Create Simple Bar Chart In Codeigniter Using AmCharts?
  • dynamic Highcharts in Codeigniter
  • Barcode in Codeigniter
  • Codeigniter Interview Questions
  • Project
Home » Codeigniter » 

Form validation


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(); ?>




    Itechtuto

    Connect Us Socially:

    Quick Links

    • itech
    • About Us
    • Feedback
    • Trademarks
    • Privacy Policy
    • Terms of Use
    • Sitemap
    • Trademarks
    • Privacy Policy
    • Terms of Use
    • Sitemap

    Copyright © 2016 itechxpert (P) Ltd. All rights reserved.

    Copyright © 2016 itechxpert (P) Ltd. All rights reserved.