【问题标题】:Laravel Form validation with logic operators使用逻辑运算符进行 Laravel 表单验证
【发布时间】:2016-10-22 11:50:08
【问题描述】:

当用户填写 Message (textarea) 时,他/她无法填写 Date、Time、Venue 值。
仅当 Message 为空且所有这三个字段均已填充时,才会考虑这三个字段。
如何使用 Laravel 表单验证来做到这一点?是否可以在 Request 的 rule 方法中定义这些逻辑?
我是 Laravel 的新手。
提前致谢

【问题讨论】:

  • 因此,您需要由用户填写的消息字段或仅这三个字段。但不是他们四个都在一起吗?有人要求填写完整吗?
  • 是的,不是所有四个都在一起。

标签: forms validation request laravel-5.2 rules


【解决方案1】:

正如您所说,必须填写“消息”字段或所有这三个字段(“日期”、“时间”、“地点”)之类的验证规则。所以规则应该如下所示。

$rules = [
            'date'    => 'required_with_all:time,venue|required_without:message',
            'time'    => 'required_with_all:date,venue|required_without:message',
            'venue'   => 'required_with_all:date,time |required_without:message',
            'message' => 'required_without_all:date,time,venue',
            ];

【讨论】:

    【解决方案2】:

    您可以通过使用条件验证规则来实现这一点(服务器端):

    • required_if:anotherfield,value,...
    • required_unless:anotherfield,value,...
    • required_with:foo,bar,...
    • required_with_all:foo,bar,...
    • required_without:foo,bar,...
    • required_without_all:foo,bar,...

    我会说你的情况:

    • 日期 是必需的,除非消息已填写
    • 时间是必需的,除非消息被填写
    • venue 是必填项,除非消息已填写
    • message 是必需的,没有所有日期、时间、地点

    如果需要,可以用管道分隔规则链

    遵循一个示例 sn-p。在您的 ExampleFormRequest 中使用此方法扩展 Request

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [];
    
        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
            case 'POST':
                $rules = [
                    'date'    => 'required_without:message',
                    'time'    => 'required_without:message',
                    'venue'   => 'required_without:message',
                    'message' => 'required_without_all:date,time,venue',
                    ];
                break;
            default:
                // Perform no alteration to rules
                break;
        }
    
        return $rules;
    }
    

    结帐documentation here

    【讨论】:

    • Validator.php 第 2999 行中的 InvalidArgumentException:验证规则 required_unless 至少需要 2 个参数。
    • @Sachith 你是对的,对不起。我改变了规则,应该是required_without而不是required_unless,因为前者不评估价值,只是存在。
    • 我试过更新答案,什么都没有。仍然得到两者。
    • 你能发布异常吗?不能又是required_unless……到底是哪个?
    • 不,这次没有显示错误,重定向到页面,但没有任何数据。
    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2021-01-18
    相关资源
    最近更新 更多