IRONLORD
IRONLORD

Reputation: 163

Laravel 4 validators - Validate one of two fields

Is there any generic Laravel validator option that allows me to do the example below?

Example: I have two text boxes, at least one of them must be filled. One has to be compulsorily filled, but not required are the two filled.

Upvotes: 1

Views: 3410

Answers (2)

Unnawut
Unnawut

Reputation: 7578

Looks like Laravel has some built-in rules: required_without and required_without_all.

required_without:foo,bar,...

required_without:foo,bar,... The field under validation must be present only when any of the other specified fields are not present.

required_without_all:foo,bar,...

required_without_all:foo,bar,... The field under validation must be present only when the all of the other specified fields are not present.

So in your validation you do:

$validator = Validator::make(
    [
        'textbox1' => Input::get('textbox1'),
        'textbox2' => Input::get('textbox2'),
    ],
    [
        'textbox1' => 'required_without:textbox2',
        'textbox2' => 'required_without:textbox1',
    ]
);

Upvotes: 6

The Alpha
The Alpha

Reputation: 146191

In your case, I think a little hack is easier than extending the Validator class:

if(empty(Input::get('textbox1')) && empty(Input::get('textbox2'))) {
    $v = Validator::make([], []); // Pass empty arrays to get Validator instance

    // manually add an error message
    $v->getMessageBag()->add('textbox2', 'Required if textbox1 is empty!');

    // Redirect back with inputs and validator instance
    return Redirect::back()->withErrors($v)->withInput();

}

So, if both fields are empty then after redirecting, the second text box (textbox2) will show the error message Required if textbox1 is empty!. But it could be done using conditional validation too:

$v = Validator::make([], []); // Pass empty arrays to get Validator instance

// If both fields are empty then textbox2 will be required
$v->sometimes('textbox2', 'required', function($input) {
    return empty(Input::get('textbox1')) && empty(Input::get('textbox2'));
});

$messages = array( 'required' => 'Required if textbox1 is empty!' );
$v = Validator::make(Input::all(), $rules, $messages);
if($v->passes) {
    // ...
}

Upvotes: 1

Related Questions