views:

42

answers:

2

How can I validate a form using regex in codeiginiter. I'd like to check the input against:

^([0-1][0-9]|[2][0-3]):([0-5][0-9])$

I'm assuming the best way is in some sort of callback. I tried a bunch of ideas on the web but I can't seem to get any working.

A: 

How about using AJAX?

$("form").submit(function(e) {
    e.preventDefault();
    $.post("<?php echo base_url(); ?>regex_check", { username: $("#username").val() }, function (data) {
        alert(data);
    });

The regex_check function would have a typical regex check in it, like

function regex_check(){
    $this->get->post('username');
    if(eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-] +\.[a-zA-Z.]{2,5}$', $username)){
       return TRUE;}else{return FALSE;}
    }

You would only allow successful submission of form if all data is validated.

These code snippets should help you on the track to validating the data.

Kieran Andrews
+1  A: 

You can create a function like this:

function validateRegex($input)
{
  if (preg_match('/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/', $input))
  {
    return true; // it matched, return true or false if you want opposite
  }
  else
  {
    return false;
  }
}

In your controller, you can use it like:

if ($this->validateRegex($this->input->post('some_data')))
{
  // true, proceed with rest of the code.....
}
Sarfraz