Welcome Guest, Not a member yet? Register   Sign In
Form Validation To Check Min and Max values in two fields
#1

[eluser]hema[/eluser]
Hi All,

I am having a form which is having min_cost and max_cost as two fields. max_cost field value should always be bigger than min_cost. How can i do this CI validation

Following is my code

Code:
$this->form_validation->set_rules('cost-min', 'Cost Min', 'required|numeric'); // should always be lower than cost-max
$this->form_validation->set_rules('cost-max',  'Cost Max', 'required|numeric'); // should always be higher


// above validation is normal one check if the fields are empty. Below code is to check which value is higher

if( $this->input->post('cost-min') >  $this->input->post('cost-max'))
   {
    $this->form_validation->set_message('cost-max', 'Your validation message.');
   }

Above code is not working, is there anything i can do?
#2

[eluser]TheFuzzy0ne[/eluser]
Your rules:
Code:
$this->form_validation->set_rules('cost-min', 'Cost Min', 'required|numeric'); // should always be lower than cost-max
$this->form_validation->set_rules('cost-max',  'Cost Max', 'required|numeric|callback__more_than[cost-min]'); // should always be higher

In your controller, add the following method.
Code:
function _more_than($str, $field='')
{
    // Don't run bother checking if we have a form error on cost-min.
    if  (form_error('cost-min')) {
        return true;
    }

    $str = intval($str);
    $min = intval($this->input->post($field));
    
    if ($str <= $min) {
        $this->form_validation->set_message('_more_than', "The %s field must be more than {$min}.");
        return false;
    }
    
    return true;
}

I've not tested it, but it should give you something to go on.

Hope this helps.
#3

[eluser]hema[/eluser]
thanks man, its working fine after remove this part

Code:
if  ( ! form_error('cost-min')) {
        return true;
    }
#4

[eluser]TheFuzzy0ne[/eluser]
Sorry. I've corrected the code so it should work now. I put a '!' in there that shouldn't be there, which was why it was causing you problems. That line ensures it doesn't run if there's a validation error from the first field. it's pointless running it if we don't have a valid cost-min.

Please use the new code. That should work fine now. Smile




Theme © iAndrew 2016 - Forum software by © MyBB