Once run check rule if another passes in Laravel 5

I have the following rules in my 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 want the valid_date rule to fire if the regex validation returns true. If the regex check returns false, then there is no point in doing the valid_date check and if there is no / present in the value, then it will be wrong when it tries to explode on /

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

+3


source to share


2 answers


You can use the method sometimes () .

$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 fire if apply_regex($input->dob)

true. Note apply_regex

if your custom function that evaluates the valuedob

+1


source


you can try the bail rule,



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

      

0


source







All Articles