I need to validate a request where if field1
is present, then field2
should be empty and vice versa. How can i achieve this in Laravel?
Asked
Active
Viewed 532 times
0

Karl Hill
- 12,937
- 5
- 58
- 95
-
there are similar answers regarding that, what have you tried so far? – bhucho Feb 17 '21 at 08:38
-
@KarlHill the value can be empty – Feb 17 '21 at 08:48
-
@bhucho i plan to use custom validator, but i would like to know if there is a laravel way of doing this – Feb 17 '21 at 08:48
-
Simple jquery on the front for this and pretty easy logic in your controller when posting. – Apr 19 '22 at 16:48
2 Answers
0
You can try this:
$rules = array(
'field1' => 'required_without:field2',
'field2' => 'required_without:field1',
);

Kaleem Shoukat
- 811
- 6
- 14
-
checkout this link you will find your answer. https://stackoverflow.com/questions/48420718/required-field-only-if-another-field-has-a-value-must-be-empty-otherwise – Kaleem Shoukat Feb 17 '21 at 11:47
0
From Laravel Docs:
#prohibits:anotherfield,...
If the field under validation is present, no fields in another field can be present, even if empty.
I think this is what you want:
public function rules()
{
return [
'field1' => 'prohibits:field2',
'field2' => 'prohibits:field1',
}
What does this means?
Based on the sample code above we can know once field1
is present, field2
is not allowed to be present. Likewise, once field2
is present, field1
is not allowed to be present.
Hopefully, this can help you.

yungts
- 1