Codeigniter表单验证无法与自定义回调函数一起使用 [英] Codeigniter form validation not work as espected with custom callback function

查看:97
本文介绍了Codeigniter表单验证无法与自定义回调函数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了Codeigniter的内置表单验证库来验证电子邮件输入字段。

I used Codeigniter's built-in form validation library to validate a email input field.

这是我的验证规则:

$this->form_validation->set_rules('email', '<b>email</b>', 'trim|htmlspecialchars|required|valid_email');

使用上述验证规则时,所有操作均按照我的预期进行。

When using above validation rule everything is worked the way I espected.

例如:


  • 如果输入字段为空,则显示:必填电子邮件。

  • 如果用户输入的电子邮件无效,则会显示:电子邮件无效。

然后我添加了自定义表单验证规则通过添加回调函数。

Then I added custom form validation rule by adding callback function.

这是我修改过的验证规则:

This is my modified validation rule:

$this->form_validation->set_rules('email', '<b>email</b>', 'trim|htmlspecialchars|required|valid_email|callback_mail_check');

而且,这是我的回调函数:

And, This is my callback function:

public function mail_check() {

        if (!$this->users_model->get_user_by_email_address($this->input->post('email', TRUE))) {

            $this->form_validation->set_message('mail_check', 'Your <b>email</b> could not be found.');
            return FALSE;

        } else {
            return TRUE;
        }

    }

现在,当我提交表格而不填写电子邮件字段或使用无效电子邮件提交,其总是输出自定义回调函数的验证消息(找不到您的电子邮件。)。

Now when I submit form without filling email field or submit with invalid email, its always out put custom callback function's validation message(Your email could not be found.).

但是这不是我想要的方式。

But its not the way I wanted.

我想先验证电子邮件字段中的空值,然后在回调函数之后验证有效电子邮件。

I want to first validate email field for empty values, then for valid email, after that callback_function.

推荐答案

您使用的验证规则正确。只需删除一些不需要的规则

The validation rules you are using are correct. Just remove few rules those are not required

$this->form_validation->set_rules('email', '<b>email</b>', 'required|valid_email|callback_mail_check');

回调会自动添加当前验证的参数。您不需要从GET / POST方法中读取它。

The callback automatically add the parameter of current validation. You don't need to read it from GET/POST method.

public function mail_check($email)
{
    if (!$this->users_model->get_user_by_email_address($email)) {

        $this->form_validation->set_message(__FUNCTION__, 'Your <b>email</b> could not be found.');
        return false;
    }
    return true;
}

这篇关于Codeigniter表单验证无法与自定义回调函数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆