How to use sometimes rule in Laravel 5 request class

There is a documented way to make changes to the request's validator instance in Laravel 5.4. You should implement the withValidator method for that.

Based on the example from @lukasgeiter's answer, you may add the following to your request class:

/**
 * Configure the validator instance.
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->sometimes('dob', 'valid_date', function ($input) {
        return apply_regex($input->dob) === true;
    });
}

By doing this you don't have to worry about overriding internal methods. Besides, this seems to be the official way for configuring the validator.


You can attach a sometimes() rule by overriding the getValidatorInstance() function in your form request:

protected function getValidatorInstance(){
    $validator = parent::getValidatorInstance();

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

    return $validator;
}