Sasanka Panguluri
Sasanka Panguluri

Reputation: 3128

Laravel - Use validation rule inside Custom Validation

I am writing a custom validation rule on Laravel 4. However, I am looking forward to use the existing validation rules ( example : exists, email, min etc. ) inside it. I am not sure how to do this, and I am guessing using Validator::make is not really the right way. My code is below:

    Validator::extend('check_fulfilled',function($attribute,$value,$parameters){
        $movieidfield = Input::get('movieid');
                if(     empty($movieidfield )    ) return false;
                    // Here I would like to test $movieidfield 
                    //with exists and min validation rules 
    });

It would be really great if someone can help me with this. Thank you!

Upvotes: 5

Views: 5136

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38932

Validation rules are composable.

A custom validation rule like yours shouldn't need to get values from the Input parameter bag. Validator class already takes care of that.

Validator::extend('check_fulfilled', function($attribute, $value, $parameters) {
    return !empty($value);
});

For example, to use your custom validation rule with other existing rules you could write when instantiating your Validator instance:

$v = Validator::make($data, array(
     'movieid' => 'check_fulfilled|email',
));

Unless you know what you are doing should you inline validation rules.

To achieve that, you could resolve Validator singleton in the app service container that is registered there by the ValidationServiceProvider.

Validator::extend('check_fulfilled', function($attribute, $value, $parameters) {
    if (empty($movieidfield)) return false;
    $v = App::make('validator');

    return $v->validateExists($attribute, $value, $parameters) 
           && $v->validateEmail($attribute, $value);
});

Note that the $parameters array would need to hold values for the inlined validation rules.

Refer to signature of the validation methods to understand what arguments to passed.

Validator::validateExists($attribute, $value, $parameters)

Validator::validateEmail($attribute, $value)

Validator::validateMin($attribute, $value, $parameters)

Upvotes: 0

Related Questions