简体   繁体   中英

Codeigniter form validation greater than field one and less than field two

How to create form validation in Codeigniter base on other field, for example I have two field (field_one, and field_two) where field_one is must be less_than field_two and field_to must be greater_than field_one.

$this->form_validation->set_rules('field_one', 'Field One', 'less_than[field_two]');

$this->form_validation->set_rules('field_two', 'Field Two', 'greater_than[field_one]');

my code is doesn't work, the error always displaying

'Field two must be greater than field one'

but I input the right way,

field one 1 field two 4

how to solve this? Plz help me!

Try this like

    $this->form_validation->set_rules('first_field', 'First Field', 'trim|required|is_natural'); 
$this->form_validation->set_rules('second_field', 'Second Field', 'trim|required|is_natural_no_zero|callback_check_equal_less['.$this->input->post('first_field').']');

And callback as :

 function check_equal_less($second_field,$first_field) 
{ if ($second_field <= $first_field) { $this->form_validation->set_message('check_equal_less', 'The First &amp;/or Second fields have errors.'); 
return false; }
 else { return true; } 
}

Instead of

'greater_than[field_one]'

use

'greater_than['.$this->input->post('field_one').']'

I just tried it out and it works. Thanks to Aritra

Native greater_than method need a numeric input, so we can't use greater_than[field_one] directly. But we can make a custom method to achieve the goal.

My way are as follows:

/* A sub class for validation. */
class MY_Form_validation extends CI_Form_validation {

    /* Method: get value from a field */
    protected function _get_field_value($field)
    {
        return isset($this->_field_data[$field]["postdata"])?$this->_field_data[$field]["postdata"]:null;
    }

    /* Compare Method: $str should >= value of $field */
    public function greater_than_equal_to_field($str, $field)
    {
        $value = $this->_get_field_value($field);
        return is_numeric($str)&&is_numeric($value) ? ($str >= $value) : FALSE;
    }
}

All validation data save in the protected variable $_field_data, and value save in the key "postdata", so we can take the value of the field we want.

When we have above method, we can use 'greater_than_equal_to_field[field_one]' to do the validation between two fields.

  • A good reference - Native form validation methods matches and differs. You can check it in CI_Form_validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM