【问题标题】:Laravel validation with custom condition带有自定义条件的 Laravel 验证
【发布时间】:2017-01-08 04:22:53
【问题描述】:

我正在尝试使用条件设置验证规则,但不知道如何执行以下操作:

在我的表单中,我有 title_url(多个语言版本的数组)。我想要唯一的 title_url 但只有当表单中的 module_cat_id 与 DB 中的现有行具有相同的值时。

这是我的规则:

'title_url.*'   => 'required|min:3|unique:modules_cat_lang,title_url'

有什么办法解决这个问题吗?

【问题讨论】:

    标签: validation laravel unique


    【解决方案1】:

    如果您想将自己的自定义验证逻辑添加到现有的 laravel 验证器,那么您可以使用 after hooks。请看下面的例子。

    参考:https://laravel.com/docs/8.x/validation#adding-after-hooks-to-form-requests

    示例1(无参数)

        $validator->after(function ($validator)  {
            if ('your condition') {
                $validator->errors()->add('field', 'Something went wrong!');
            }
        });
    

    Example 2(With Parameter) // 这里可以传入自定义参数($input)

        $validator->after(function ($validator) use ($input)  {
            if ($input) {
                $validator->errors()->add('field', 'Something went wrong!');
            }
        });
    

    【讨论】:

    • 如果我在自定义请求类中设置正常的默认规则,如何在请求类中添加这些自定义?
    【解决方案2】:

    您可以定义类似于以下代码的自定义:

    \Validator::extend('custom_validator', function ($attribute, $value, $parameters) {
            foreach ($value as $v) {
                $query = \DB::table('modules_cat_lang') // use model if you have
                    ->where('title_url', $v)
                    ->where('module_cat_id', \Input::get('module_cat_id'));
                if ($query->exists()) {
                    return false;
                }
            }
        });
    'title_url.*'   => 'required|min:3|custom_validator'
    

    在此处阅读更多信息https://laravel.com/docs/5.3/validation#custom-validation-rules

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 2020-06-03
      • 2019-07-02
      • 1970-01-01
      • 2016-10-25
      • 2015-10-02
      • 2020-07-12
      • 1970-01-01
      • 2014-11-25
      相关资源
      最近更新 更多