April 22, 2012

Is it possible to using or in codeigniter form validation?

Question by motto

I have an input which can be decimal or numeric. I want to use this rule:

$this->form_validation->set_rules('price', 'Price', 'decimal|numeric');

But i think the rules in form_validation helper not working with “or” statement. If the price is something like that “149.99” it’s valid but if the price is “150” it’s not.

Am i missing something or isn’t it possible to use something like that:

 $this->form_validation->set_rules('price', 'Price', 'decimal or numeric');

Answer by Starx

CI, does not allow to mix datatypes when validating. Instead, Create your custom validation rule.

Declare a rule like this

$this->form_validation->set_rules('price', 'Price', 'callback_decimal_numeric');

After create a method on the controller

    public function decimal_numeric($str)
    {
        if ($str <isdecimal&nummeric>) //Use your logic to check here
        {
            $this->form_validation->set_message('decimal_numeric', 'The %s field validation has failed');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!