Home > OS >  Laravel Validation rules: required_without
Laravel Validation rules: required_without

Time:10-26

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}$/',

    ];

CodePudding user response:

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.

CodePudding user response:

You're using the wrong rule. You should use required_with instead of required_without.

By docs:

required_with - docs

The field under validation must be present and not empty only if any of the other specified fields are present and not empty.

required_without - docs

The field under validation must be present and not empty only when any of the other specified fields are empty or not present.
  • Related