【问题标题】:Laravel 4 custom validation ruleLaravel 4 自定义验证规则
【发布时间】:2016-11-22 16:32:13
【问题描述】:

对于自定义验证规则是否需要返回 true 或 false 来触发,我有点困惑。

我正在验证一个电子邮件地址,以使其确实通过关系属于另一个模型。

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;
        }

});

我在上面尝试的是,查找输入的电子邮件是否存在用户,如果确实存在,则检查该电子邮件是否与任何客户相关,以及这些客户 id 是否与POST,如果电子邮件存在并且与 POST 中的客户端 ID 相关,我想返回一个错误,否则我很乐意处理 POST。

目前,我认为我允许任何事情通过。我是否正确使用了自定义规则,如果我想抛出错误应该返回什么?

【问题讨论】:

  • 看起来是正确的,你有没有把这段代码放在服务提供者里面,如果是的话,你记得把服务提供者添加到config/app.php的提供者数组吗?
  • 它现在直接在我的控制器中。
  • 只是确保表单提交到控制器的部分,而不是负责构建表单的部分?还可以尝试在设置 $user var 之前在其中添加 dd('test'); 以查看它是否曾经进入该部分。

标签: php validation laravel laravel-4


【解决方案1】:

我认为您以错误的方式处理此问题。与其为单个用例扩展 Validator 类,不如考虑简单地将消息添加到消息包中,并将输入元素作为键。例如

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

提示:我通常会在我的模型中添加一个规则数组并注入一个Validator 类,这样我就可以轻松地验证模型,而无需创建Validator 的实例或一直编写规则数组。

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 2017-04-11
    • 2018-02-18
    • 2019-02-12
    • 1970-01-01
    • 2018-05-25
    • 2016-11-14
    • 1970-01-01
    • 2014-04-22
    相关资源
    最近更新 更多