Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation rules: required_without

I have two fields: Email and Telephone

i want to create a validation where one of two fields are required and if one or both fields are set, it should be the correct Format.

I tried this, but it doesnt work, i need both though

 public static array $createValidationRules = [
        'email' => 'required_without:telephone|email:rfc',
        'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',

    ];
like image 958
Elias Avatar asked Jul 17 '26 01:07

Elias


1 Answers

It is correct that both fields produce the required_without error message if both are empty. This error message clearly says that the field must be filled if the other is not. You may change the message if needed:

$messages = [
    'email.required_without' => 'foo',
    'telephone.required_without' => 'bar',
];

However, you must add the nullable rule, so the format rules don't apply when the field is empty:

$rules = [
    'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
    'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];

Furthermore: It is recommended writing the rules as array, especially when using regex.

like image 175
halloei Avatar answered Jul 18 '26 15:07

halloei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!