我只需要验证如何检查用户输入是否等于某个字符串。
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;
}
}
你可以创建一个函数来过滤单词,以及
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