Reputation: 1998
I have 2 (contact telephone and contact mobile) fields in a form which either A OR B need to be filled.
I'm validating the form using laravel request validation and the required_without
rule, which looks like this.
'contact_telephone' => 'required_without:contact_mobile',
'contact_mobile' => 'required_without:contact_telephone',
So with this code it specifies that one of the 2 fields must be filled.
The error is that if I try to submit the form without filling either one in, the error message shows twice.
How would I show the message just once? Or is there a better rule to achieve this instead of required_without
that i'm missing?
Upvotes: 3
Views: 1281
Reputation: 1998
After playing around with it, I realised that only 1 of the required_without
are actually required.
The logic is quite simple, the required validation (whatever one used) only fires for empty fields. If I specify that the contact telephone is required when the mobile is empty like so
'contact_telephone' => 'required_without:contact_mobile',
Then it will work for all 3 possible options.
If I fill out the mobile and not the telephone then the mobile is no longer empty and the telephone field isn't required anymore (Passes validation).
If I fill neither out, then the mobile is empty, and the telephone is then required, thus displaying 1 error message (Fails Validation).
If I fill out the telephone then it does not worry about the mobile validation as the telephone is not empty anyway (Passes validation).
This means that either one of the 2 fields are required, but it will only display 1 error message and requires 1 rule.
Upvotes: 2
Reputation: 35337
Just an alternative approach that may solve your problem.
Use an array for contact instead of having contact_phone
and contact_telephone
, use contact[telephone]
and contact[mobile]
.
Then you can use the validation rule of:
'contact' => 'required|array|min:1'
Your message for contact could then be You must fill in either the telephone number or the mobile number
.
Upvotes: 2