簡體   English   中英

Codeigniter表單驗證大於第一個字段,小於第二個字段

[英]Codeigniter form validation greater than field one and less than field two

如何在Codeigniter中基於其他字段創建表單驗證,例如我有兩個字段(field_one和field_two),其中field_one必須小於field_two,field_to必須大於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]');

我的代碼不起作用,錯誤始終顯示

“第二場必須大於第一場”

但我輸入正確的方式

場一1場二4

如何解決呢? 請幫我!

像這樣嘗試

    $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').']');

和回調為:

 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; } 
}

代替

'greater_than[field_one]'

采用

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

我只是嘗試了一下,而且效果很好。 感謝阿里特拉

本機的great_than方法需要數字輸入,因此我們不能直接使用Greater_than [field_one]。 但是我們可以通過自定義方法來實現目標。

我的方法如下:

/* 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;
    }
}

所有驗證數據都保存在受保護的變量$ _field_data中,值保存在鍵“ postdata”中,因此我們可以獲取所需字段的值。

當我們擁有上述方法時,我們可以使用'greater_than_equal_to_field [field_one]'在兩個字段之間進行驗證。

  • 一個很好的參考-本機表單驗證方法匹配並且有所不同。 您可以在CI_Form_validation中進行檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM