【问题标题】:Laravel 5.5 / Validator / Custom rulesLaravel 5.5 / 验证器 / 自定义规则
【发布时间】:2018-05-25 00:15:34
【问题描述】:

(为了更清晰的目的而编辑)

几个月前我发现了 Laravel,并关注了一些 Laracast 视频。现在,我遇到了自定义验证器的问题。

我有正常和永久的规则(日期 | 要求 | 最小/最大)来验证我的表单请求。这部分有效。

但我有一个自定义验证,如果请求参数之一 - select1 - 设置为 1(例如),则可以将其验证为正常规则。

我看了十几个解释,但都不够清楚。

那么,让我们从我的代码开始吧。谢谢你的宽容... 我的问题是底部的 customTest 函数。

谢谢,

1/ 我提出了一个新的请求

php artisan make:controller priceRequest.php

2/ 我制定了一些规则并更改了一些行。

public function authorize()
{
    return true;
}

// Permanent RULES
public function rules()
{
    $rules = [
        'field1' => 'required|min:1|max:15',
        'field2' => 'required',
        'date1' => 'required|date',
        'select1' => 'required',
    ];

    return $rules;
}

然后我集成了一个新功能来执行自定义验证

public function withValidator($validator) {
    $validator->after(function ($validator) {
        if (!$this->customTests($this->request->get('data'))){
            $validator->errors()->add('custom', 'Something is wrong');
        }
    });
}

最后,我写了 customTests 函数,我被困在这个函数里面了!!

public function customTests($data) {

    if ($data['select1'] == 1) {

        // HERE MY QUESTION
        // I'd like to verify that $data['date2']
        // is a date and is set. So, I'd like to
        // add a rule to rules (has I made with
        // 'date1' => 'required|date',
        // and return TRUE if the rule match or
        // FALSE

    }
}

【问题讨论】:

  • 问题是什么?
  • 对不起,问题在代码中:-(
  • 尝试用其他方式定义它。没有人知道你需要什么。
  • 你好亚当,我想我已经够清楚了。关于问题 B,我想在规则函数中添加一个“正常”规则,而不是编写测试来检查日期。我不知道如何将此规则添加到验证器。我检查了: $v = Validator::make($data, [ 'email' => 'required|email', 'games' => 'required|numeric', ]);但我不知道在 $data 变量中传递什么。

标签: laravel validation


【解决方案1】:

所以,我找到了解决问题的方法。

我犯了一个错误和困惑,因为我试图将新规则添加到 ->after() 函数中。

所以,正确的代码如下:

public function withValidator($validator)
{
    $validator->sometimes('ticket.price', 'required|integer|min:0.1', function ($input) {
    if ($any_condition_who_need_to_verify_new_rule) {
        return true;
    }
    else {
        # Everything is perfect, this rule cas be omitted
    }

    $validator->after(function ($validator) use ($ticket) {

        /* New test more complicated which cannot be
           tested with a rule */
        if ($this_test_is_complex_and_fails) {
            $validator->errors()->add('validateTicket', 'This is another problem');
            return false;
        }
    });
    return $validator;
}

【讨论】:

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