Search code examples
codeignitercodeigniter-2

How to validate time input in Codeigniter


I have a text box in a form to enter time and I use to check the validation using jquery. But now I want to check the validation of the text box using the codeigniter's built-in validation system. Would you please kindly tell me how to validate time input using codeigniter's built-in validation system?

Here's the code how I use to do it using jquery:

<script type="text/javascript">

$().ready(function() {

$.validator.addMethod("time", function(value, element) {  
return this.optional(element) || /^(([0-1]?[0-2])|([2][0-3])):([0-5]?[0-9])\s(a|p)m?$/i.test(value);  
}, "Enter Valid Time");

    $("#theForm").validate({
            rules: {
                    time: "required time",
            },

    });

 });

</script>

And here is the html

<input class="time" type="text" name="time1" size="15">

Solution

  • Something like this perhaps

    // Validation rule in controller
    $this->form_validation->set_rules('time', 'time', 'trim|min_length[3]|max_length[5]|callback_validate_time');
    

    and a callback:

    public function validate_time($str)
    {
    //Assume $str SHOULD be entered as HH:MM
    
    list($hh, $mm) = split('[:]', $str);
    
    if (!is_numeric($hh) || !is_numeric($mm))
    {
        $this->form_validation->set_message('validate_time', 'Not numeric');
        return FALSE;
    }
    else if ((int) $hh > 24 || (int) $mm > 59)
    {
        $this->form_validation->set_message('validate_time', 'Invalid time');
        return FALSE;
    }
    else if (mktime((int) $hh, (int) $mm) === FALSE)
    {
        $this->form_validation->set_message('validate_time', 'Invalid time');
        return FALSE;
    }
    
    return TRUE;
    }