簡體   English   中英

Codeigniter Form-Validation:驗證輸入是否等於某個字符串

[英]Codeigniter Form-Validation: Validate if input is equals to a certain string

我只需要驗證如何檢查用戶輸入是否等於某個字符串。

public function check_input()
{
   $input_str = $this->input->post("input_str", TRUE);

   $this->form_validation->set_rules("input_str, "Input String", "trim|required| validate if $input_str is equals to the string 'FOO' ");

   if ($this->form_validation->run() == FALSE)
   {
       // if input_str != 'FOO', do something
   }
   else
   {
       // do something
   }
}

您需要進行callback function ,然后檢查該值是否等於'foo' ,您還需要將case更改為小寫,這樣如果用戶寫入大寫字母就不會造成任何錯誤。 我已經為您的問題寫了一個可能的解決方案,必要時會提到評論。 看看它是否對你有幫助。

public function check_input(){

    $this->form_validation->set_rules("input_str", "Input String", "trim|required|callback__checkstring"); // call to a function named _checkstring

    if ($this->form_validation->run() == FALSE){

        // if input_str != 'FOO', do something
    }
    else{

        // do something
    }
}

function _checkstring(){

    $input_str = strtolower($this->input->post("input_str", TRUE)); // get the post data and convert it to lowercase

    if($input_str !== 'foo'){

        $this->form_validation->set_message('_checkstring','Please enter the correct value!');  //set message to the callbacked function(ie _checkstring) not the input field here.
        return FALSE;

    }else{

        return TRUE;
    }
}

您可以制作一個function來過濾單詞,並且

public function username_check($str)
{
    if ($str == 'test')
    {
        $this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

並在您的 set_rules 中調用它

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');

有關詳細信息,您可以查看文檔頁面https://codeigniter.com/userguide3/libraries/form_validation.html#callbacks-your-own-validation-methods

暫無
暫無

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

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