5
votes

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!

1
Presumably you could instantiate your own validator inside that function and use that to test the value at hand?alexrussell
Thanks, how do I do that?Sasanka Panguluri
Juts the normal way you'd use a validator as if in a controller. $v = Validator::make(), etc.alexrussell
@SasankaPanguluri answered?Dionysios Arvanitis

1 Answers

0
votes

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)