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'