【问题标题】:CodeIgniter validation always returns false on matches actionCodeIgniter 验证总是在匹配操作上返回 false
【发布时间】:2023-03-03 10:43:02
【问题描述】:

我在当前项目中使用了 CodeIgniter 3.1.0。对于表单验证,一切正常,但是当我想使用matches 作为规则时我遇到了问题。这是我的 HTML:

<input type="password" class="form-control" name="password" id="password">
<input type="password" class="form-control" name="confirm" id="confirm">  

这是我的控制器:

$this->form_validation->set_rules('password','Password','matches[confirm]');
if ($this->input->post('password') != '' && $this->form_validation->run() == FALSE) {
    echo 'Error';
}

即使我在两个字段中输入相同的值,我总是得到错误结果。我的错误是什么?

【问题讨论】:

  • 如果没有定义,请在构造函数中使用$this-&gt;load-&gt;library('form_validation');
  • 我没有看到$this-&gt;form_validation-&gt;set_rules('confirm','Confirm','required');
  • @Virb 我在我的代码中做到了。我在这个文件中有几个验证,但我只有上面描述的问题
  • 你的 form_open 使用表单助手或表单标签怎么样,你设置正确了吗
  • @wolfgang1983 在该页面中更新密码不是必需的操作。

标签: php forms codeigniter validation match


【解决方案1】:

如果可行,这会很有帮助。

如果您的matches 有问题。做一件事,创建像matches_pass 这样的函数并使用如下:

$this>form_validation>set_rules("input[password]","Password",'required|matches_pass[input---conf_password]');

还有你的功能,

public function matches_pass($str, $field)
{
    $field = explode('---',$field);
    if ( ! isset($theField = $_POST [$field[0] ][ $field[1] ]))
    {
        return FALSE;
    }  
    return ($str !== $theField) ? FALSE : TRUE;
}

然后把它放在你的图书馆里。

【讨论】:

  • 框架自己构建的时候为什么要使用这样的代码?
  • 不知何故,在某些时候 CI 核心输入无法解决这个问题。但我正在检查为什么会这样。
【解决方案2】:

在 if 条件下会提到 ($this->input->post('password') != '')。所以无论你插入什么值,它都会执行为真。

if ($this->input->post('password') != '' && $this->form_validation->run() == FALSE) {
        echo 'Error';
    }

我建议你这样做

public function index()
{
$this->load->helper(array('form', 'url'));

$this->load->library('form_validation');

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

$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');

if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}

正如http://www.codeigniter.com/userguide2/libraries/form_validation.html中提到的那样

【讨论】:

    【解决方案3】:

    当您尝试匹配时,您还必须验证其他字段,这是它可以帮助您的代码。

    $this->form_validation->set_rules('password', 'password', 'trim|required');
    $this->form_validation->set_rules('confirm', 'confirm', 'trim|required|matches[password]');
    if ($this->form_validation->run() == FALSE) {
         echo 'ERROR';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多