问题
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