简体   繁体   English

Laravel 4自定义验证规则

[英]Laravel 4 custom validation rule

I am little confused as to whether a custom validation rules needs to return true or false to fire. 对于自定义验证规则是否需要返回true或false来激发,我几乎不感到困惑。

I am validating an email address to make that it does already belong to another model via a relationship. 我正在验证一个电子邮件地址,以使其通过关系已经确实属于另一个模型。

Validator::extend('email_exists', function($attribute, $value, $parameter){
        $user = User::where('email', '=', $value)->with('clients')->first();
        //Does the user exits, and are they already a member of this client?
        //We know this by looking at the client id, and comparing them the current ID.
        if($user != NULL) {
            if(in_array(Input::get('client_id'), $user->clients->lists('id'))) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }

});

What I am trying to above is, find if a user exists with the entered email, if it does exist, then check if the email is related to any clients, and if any of those clients id match the client id in the POST, if the email exists and is related to client id in the POST I want to return an error, other wise I happy for the POST to processed. 我在上面要尝试的是,查找输入的电子邮件中是否存在用户,如果存在,然后检查该电子邮件是否与任何客户端相关,并且这些客户端ID中的任何一个与POST中的客户端ID相匹配,如果电子邮件存在并且与POST中的客户端ID有关,我想返回一个错误,否则我很乐意处理POST。

At the moment, I think I am allowing anything through. 目前,我认为我允许任何事情通过。 Am I using the custom rule correctly, and what should return if I want to throw an error? 我是否正确使用了自定义规则?如果我想抛出错误,应该返回什么?

I think you're approaching this the wrong way. 我认为您正在以错误的方式进行处理。 Instead of the stress of extending the Validator class for a singular use case, you should consider simply adding a message to the message bag with your input element as the key. 您不必考虑为单个用例扩展Validator类,而应考虑将输入元素作为键,将一条消息简单地添加到消息包中。 eg 例如

$validator->messages()->add('client_id', 'This email is already associated with a client');

Tip: I usually add a rules array to my models and inject a Validator class so I can easily validate the model without having to create an instance of the Validator or writing a rules array all the time. 提示:我通常将规则数组添加到模型中并注入Validator类,这样我就可以轻松验证模型,而不必始终创建Validator的实例或编写规则数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM