This tutorial shows how to work with custom validation in Codeigniter. We need many times that a field has to be validated against some type of values but built-in features do not provide all kind of validation pattern, so we need to write a function which will be used as callback function for a particuler input field for validation purpose. The below example validates the date field and if the date is invalid then it displays an appropriate error message to the user.
View part: application/views/date.php

<title>Custom validation in Codeigniter</title>        
    <?php
        echo form_open($this->uri->uri_string());
        if (validation_errors()) {
            echo '<div class="n_error">';
            echo validation_errors();
            echo '</div>';
        }
    ?>
    <div>
        <label for="exp_start_date">Start Date <span class="red">(required)</span></label>
        <input id="start_date" name="start_date" class="text" value="<?php echo set_value('start_date'); ?>" type="text" />
    </div>
    <div>
        <input name="verify" id="verify" class="button verify" value="Verify" type="submit" />
    </div>
    <?php
        echo form_close();
    ?>

 

Controller part:

function verify_date() {
    if ($this->input->post('verify')) {
        $this->form_validation->set_rules('start_date', 'Start Date', 'trim|required|max_length[10]|xss_clean|callback_is_start_date_valid');
    }
    $this->load->view('date');
}

Usage Example

function is_start_date_valid($date) {
    if (date('Y-m-d H:i:s', strtotime($date)) == $date) {
        return TRUE;
    } else {
        $this->form_validation->set_message('start_date', 'The %s Start date must be in format "yyyy-mm-dd hh:mm:ss"');
            return FALSE;
    }
}

 

That’s all. Thanks for your reading. Please do not forget to leave a comment.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *