required_without not working with other rules
Asked Answered
I

2

5
'person.mail' =>'required_without:person.phone|sometimes|email|unique:persons,mail',

'person.phone' => 'required_without:person.mail|sometimes|regex:/[0-9]/|size:10|unique:persons,phone'

i need to validate phone and mail, one of them is mandatory

when the mail is empty and the phone isn't, the validation fails at the email rule and this goes both ways, when the mail is present and phone empty, it fails at the regex rule

how can i stop validation if value is null?

Inflectional answered 24/8, 2017 at 20:19 Comment(0)
W
7

As the laravel docs state:

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list.

I get the feeling that you actually do post both person[email] and person[phone], in which case sometimes will instruct validation to continue, since the values will then be empty strings (or maybe null) rather than not present. You can conditionally add rules on other assertions than check whether key x exists by creating your own validator, and use its sometimes() method to create your own assertions:

$v = Validator::make($data, [
    'person.email' => 'email|unique:persons,mail',
    'person.phone' => 'regex:/[0-9]/|size:10|unique:persons,phone',
]);

$v->sometimes('person.email', 'required', function($input) {
    return ! $input->get('person.phone');
});

$v->sometimes('person.phone', 'required', function($input) {
    return ! $input->get('person.email');
});

The difference here is that the fields are not by default required. So for example, person.phone may either be empty, or must match your regex. If $input->get('person.email') returns a falsy value, person.phone is required after all.

As a note, I think your regex is wrong. It will pass as soon as any character inside person.phone is a number. I think you're looking for something like this:

'person.phone' => 'regex:/^[0-9]{10}$/|unique:persons,phone'
Witcher answered 24/8, 2017 at 20:51 Comment(1)
yep, i read somewhere on the laracasts forum that sometimes rule evaluates empty string and null as false, thank you for your answerInflectional
I
0

i worked it around like this, it's not the best way, but it works just fine after the validation i added

if(empty($request->all()['person']['mail']) && empty($request->all()['person']['phone'])){
        $validator->errors()->add('person.mail', 'Mail or phone required');
        $validator->errors()->add('person.phone', 'Mail or phone required');
        return redirect("admin/people-create")->withInput()->withErrors($validator);
    }
Inflectional answered 24/8, 2017 at 23:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.