Reputation: 390
'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?
Upvotes: 5
Views: 3644
Reputation: 7916
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'
Upvotes: 7
Reputation: 390
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);
}
Upvotes: 0