Codeigniter 表单验证:如果规则失败,则停止验证以下规则
Codeigniter Form validation: Stop validating following rules if a rule fails
这是我处理用户输入的控制器方法
function do_something_cool()
{
if ($this->form_validation->run() === TRUE)
{
// validation passed process the input and do_somthing_cool
}
// show the view file
$this->load->view('view_file');
验证规则如下:
<?php
$config = array(
'controller/do_something_cool' => array(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback_check_email_exists',
)
)
);
我的问题:
如果用户输入不是有效的电子邮件,则验证规则不会停止执行下一条规则,在这种情况下为回调函数。因此,即使电子邮件无效,我也会收到 check_email_exists() 回调的错误消息。
CI 中是否有任何选项可以在规则失败时停止检查其他规则?
来自system/libraries/Form_validation.php
的_prepare_rules()
方法,
"Callbacks" are given the highest priority (always called), followed
by 'required' (called if callbacks didn't fail), and then every next
rule depends on the previous one passing.
这意味着,输入将首先根据回调进行验证。所以我们必须检查回调函数本身的输入。
针对上述情况,我修改了我的回调函数如下
function check_email_exists($email)
{
if ($this->form_validation->valid_email($email) === FALSE)
{
$this->form_validation->set_message('check_email_exists', 'Enter a valid email');
return FALSE;
}
// check if email_exists in the database
// if FALSE, set validation message and return FALSE
// else return TRUE
}
这是我处理用户输入的控制器方法
function do_something_cool()
{
if ($this->form_validation->run() === TRUE)
{
// validation passed process the input and do_somthing_cool
}
// show the view file
$this->load->view('view_file');
验证规则如下:
<?php
$config = array(
'controller/do_something_cool' => array(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback_check_email_exists',
)
)
);
我的问题: 如果用户输入不是有效的电子邮件,则验证规则不会停止执行下一条规则,在这种情况下为回调函数。因此,即使电子邮件无效,我也会收到 check_email_exists() 回调的错误消息。
CI 中是否有任何选项可以在规则失败时停止检查其他规则?
来自system/libraries/Form_validation.php
的_prepare_rules()
方法,
"Callbacks" are given the highest priority (always called), followed by 'required' (called if callbacks didn't fail), and then every next rule depends on the previous one passing.
这意味着,输入将首先根据回调进行验证。所以我们必须检查回调函数本身的输入。
针对上述情况,我修改了我的回调函数如下
function check_email_exists($email)
{
if ($this->form_validation->valid_email($email) === FALSE)
{
$this->form_validation->set_message('check_email_exists', 'Enter a valid email');
return FALSE;
}
// check if email_exists in the database
// if FALSE, set validation message and return FALSE
// else return TRUE
}