Laravel Validation one of two fields must be filled

PhpValidationLaravelLaravel 4

Php Problem Overview


I have two fields:

QQ

Email

How do I set up a Validator object so that one of these fields must be filled? It doesn't matter which.


$messages = array(
    'email.required_without:qq' => Lang::get('messages.mustenteremail'),
    'email.email' => Lang::get('messages.emailinvalid'),
    'qq.required_without:email' => Lang::get('messages.mustenterqq'),
);

Php Solutions


Solution 1 - Php

required_without should work.

It means that the field is required if the other field is not present. If have more than two fields and only one is required, use required_without_all:foo,bar,...

$rules = array(
    'Email' => 'required_without:QQ',
    'QQ' => 'required_without:Email',
);

Solution 2 - Php

In the example above (given by lucasgeiter) you actually only need one of the conditions not both.

$rules = array(
    'Email' => 'required_without:QQ'
);

If you have both rules then filling neither in will result in TWO error messages being displayed. This way it will check that at least one field is filled in and will only display one error message if neither are filled.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionimperium2335View Question on Stackoverflow
Solution 1 - PhplukasgeiterView Answer on Stackoverflow
Solution 2 - PhpomarjebariView Answer on Stackoverflow