Laravel使用逻辑运算符进行表单验证 [英] Laravel Form validation with logic operators

查看:251
本文介绍了Laravel使用逻辑运算符进行表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户填写Message(文本区域)时,他/她无法填写Date,Time,Venue值.
仅当Message为空并且这三个字段都被填充时,这三个字段才会被考虑.
如何使用Laravel表单验证来做到这一点?是否可以在Request的rule方法中定义这些逻辑?
我是Laravel的新手.
预先感谢

When a user fill Message (textarea) he/she can't fill Date,Time,Venue values.
Those three fields will consider only when Message is empty and all those three fields are filled.
How to do this using Laravel form validation? Is it possible to define these logic in Request's rule method?
I am new for Laravel.
Thanks in advance

推荐答案

您可以通过使用条件验证规则来实现此目的(服务器端):

You can achieve this (serverside) by using conditional validation rules:

  • required_if:otherfield,value,...
  • required_unless:另一个字段,值,...
  • required_with:foo,bar,...
  • required_with_all:foo,bar,...
  • required_without:foo,bar,...
  • required_without_all:foo,bar,...

对于您的情况,我会说:

I would say for your case:

    除非填写了消息,否则需要
  • 日期
  • 除非填写了消息,否则需要
  • 时间
  • 除非填写留言,否则
  • 场地是必需的
  • 消息是必需的,没有所有日期,时间,地点
  • date is required unless message is filled-in
  • time is required unless message is filled-in
  • venue is required unless message is filled-in
  • message is required without all date, time, venue

如果需要,可以通过用管道将它们分开来束缚规则

Chain rules if you need by separating them with pipe

遵循一个示例片段.在 ExampleFormRequest 扩展Request

Follows an example snippet. Use this method inside your ExampleFormRequest extending 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;
}

结帐此处的文档

这篇关于Laravel使用逻辑运算符进行表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆