5

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!

4
  • 1
    Presumably you could instantiate your own validator inside that function and use that to test the value at hand? Commented Mar 17, 2014 at 9:53
  • Thanks, how do I do that? Commented Mar 17, 2014 at 15:24
  • 2
    Juts the normal way you'd use a validator as if in a controller. $v = Validator::make(), etc. Commented Mar 17, 2014 at 15:45
  • @SasankaPanguluri answered? Commented Jul 9, 2018 at 20:23

1 Answer 1

0

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.