Laravel Form validation with logic operators

最后都变了- 提交于 2020-01-01 10:48:15

问题


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


回答1:


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

  • 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,...

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

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

Checkout documentation here




回答2:


As you said the validation rule like the 'Message' field or all of these three ('date','time','venue') have to be filled. So the rules should look like below.

$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',
            ];


来源:https://stackoverflow.com/questions/37935804/laravel-form-validation-with-logic-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!