Minu Munasinghe
Minu Munasinghe

Reputation: 3

Codeigniter regex_match with Comparison

I have this regex_match like -

$this->form_validation->set_rules('oper_nic', 'NIC', 'trim|required|min_length[10]|regex_match[/^[0-9]{9}[vVxX]$/]');

It validate 9 number followed by one letter that is v, V, x or X.

I need to combine the above validation to an another field witch which can enter year like 1988.and validate (88) value in both fields at the same time.

Ex : Value 880989898V (According to the expression this is correct)

Another field I am entering for a separate text field the value for it is - 1993

According to the value 1993 is wrong and 1988 should be correct

because 1st value start with 88 and other value ends with 88.

How can I write a code using CodeIgniter to achieve this.

Upvotes: 0

Views: 4392

Answers (1)

aravindanve
aravindanve

Reputation: 1069

You can Write a callback function like @tpojka suggested. Here is an example:

class Form extends CI_Controller {

    public function index()
    {
        // load stuff
        // ...

        $this->form_validation->set_rules('oper_nic', 'NIC', 'trim|required|min_length[10]|regex_match[/^[0-9]{9}[vVxX]$/]');
        $this->form_validation->set_rules('year', 'Year', 'callback_year_check');

        if ($this->form_validation->run() == FALSE)
        {
            // failure
        }
        else
        {
            // success
        }
    }

    public function year_check($str)
    {
        if (substr($str, -2) == substr($this->form_validation->set_value('oper_nic'), 0, 2)) 
        {
            return true;
        } 
        return false;
    }
}

And of course I have mentioned only one validation flag for simplicity, realistically you would need something like:

$this->form_validation->set_rules('year', 'Year', 'trim|required|regex_match[/^[0-9]{4}$/]|callback_year_check');

Upvotes: 2

Related Questions