创建自定义 codeigniter 验证规则 [英] Creating a custom codeigniter validation rule

查看:34
本文介绍了创建自定义 codeigniter 验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的登录表单中有一个函数,用于检查电子邮件和密码是否与数据库中的值匹配,如果匹配,则将用户登录到系统中.

I have a function in my login form that checks if the email and password match the values in the database and if so it logs the user into the system.

如果此函数返回 false,我想显示验证错误.

I would like to display a validation error if this function returns false.

我的问题是我不确定如何创建它.该消息与密码和电子邮件字段相关,因此我不希望每个输入字段的规则只显示一条消息.

My problem is that I am unsure how to go about creating this. The message relates to both the password and email fields so I would not want a rule for each input field just display a single message.

我曾尝试使用 flashdata 来实现此目的,但它仅在页面刷新后才有效.

I have tried using flashdata to achieve this but it only works when the page has been refreshed.

如何为函数 $this->members_model->validate_member() 创建一个新的验证规则?

How can I created a new validation rule solely for the function $this->members_model->validate_member() ??

$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', '"Password"', 'trim|required');

        if ($this->form_validation->run() == FALSE)
        {
            $viewdata['main_content'] = 'members/login';
            $this->load->view('includes/template', $viewdata);
        }
        else
        {       
                if($this->members_model->validate_member())
                {

推荐答案

您在规则中使用 callback_,请参阅 回调,例如

You use the callback_ in your rules, see callbacks, for ex.

$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');

并在控制器中添加方法.此方法需要返回 TRUE 或 FALSE

and add the method in the controller. This method needs to return either TRUE or FALSE

function validate_member($str)
{
   $field_value = $str; //this is redundant, but it's to show you how
   //the content of the fields gets automatically passed to the method

   if($this->members_model->validate_member($field_value))
   {
     return TRUE;
   }
   else
   {
     return FALSE;
   }
}

然后你需要创建一个相应的错误以防验证失败

You then need to create a corresponding error in case the validation fails

$this->form_validation->set_message('validate_member','Member is not valid!');

这篇关于创建自定义 codeigniter 验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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