I have 3 fields: E-mail, telephone and mobile.
I want to set a validation rules, that one of these 3 fields are required, it doesnt matter which field.
i tried this but it doesnt work, no field is required:
public static array $createValidationRules = [
'email' => 'string|email:rfc,dns|required_without_all:mobile_phone_number,telephone',
'telephone' => 'max:15|required_without_all:mobile_phone_number,email',
'mobile_phone_number' => 'max:15|required_without_all:email,telephone',
];
$validator = Validator::make(request()->input('contact_person'), ContactPerson::getCreateValidationRules());
if($validator->fails())
return new Response($validator->errors(),
CodePudding user response:
Try something like the following:
public static array $createValidationRules = [
'email' => 'string|email:rfc,dns|nullable',
'telephone' => 'max:15|required_without_all:mobile_phone_number,email',
'mobile_phone_number' => 'max:15|required_without_all:email,telephone',
];
Not personally tested but try the following to see if it works:
public static array $createValidationRules = [
'identifier' => 'required_without_all:email,telephone,mobile_phone_number'
];
as a validation message, you could say that at least one identifier is required.
CodePudding user response:
Based on the official documentation
The field under validation must be present and not empty only when all of the other specified fields are empty or not present.
That means The only time that your code works is when all of the other fields are not present.
You can try with required_without
public static array $createValidationRules = [
'email' => 'string|email:rfc,dns|required_without:mobile_phone_number,telephone',
'telephone' => 'max:15|required_without:mobile_phone_number,email',
'mobile_phone_number' => 'max:15|required_without:email,telephone',
];
Now even if telephone is present and mobile_phone_number is not; your email field will be required.
So my guess is one of these fields are present despite you think they're not ( maybe an empty string "" or something ). You can check this with a simple dd function just before validation.
