tuscan88
tuscan88

Reputation: 5829

How to only run a validation rule if another one passes in Laravel 5

I have the following rules in a request:

Validator::extend('valid_date', function($attribute, $value, $parameters)
{
    $pieces = explode('/', $value);

    if(checkdate($pieces[1], $pieces[0], $pieces[2])) {
        return true;
    } else {
        return false;
    }
});

return [
    'first_name' => 'required',
    'last_name' => 'required',
    'email' => 'required|email|unique:users,email',
    'dob' => 'required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date',
    'mobile' => 'required',
    'password' => 'required|confirmed'
];

For the dob field I only want the valid_date rule to be run if the regex check returns true. If the regex check returns false then there is no point doing the valid_date check and if there isn't a / present in the value then it will error when it tries to explode on a /

Is there a way to conditionally add rules if another rule is valid?

Upvotes: 3

Views: 2945

Answers (2)

harunaga
harunaga

Reputation: 161

you could try the bail rule,

'dob' => 'bail|required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date',

Upvotes: 1

manix
manix

Reputation: 14747

You can make use of sometimes() method.

$v = Validator::make($data, [
    'first_name' => 'required',
    'last_name' => 'required',
    'email' => 'required|email|unique:users,email',
    'dob' => 'required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
    'mobile' => 'required',
    'password' => 'required|confirmed'
]);

$v->sometimes('dob', 'valid_date', function($input)
{
    return apply_regex($input->dob) === true;
});

valid_date will be triggered if apply_regex($input->dob) is true. Note, apply_regex if your custom function that evaluates the value of dob

Upvotes: 1

Related Questions