Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.5] Support custom validation rule objects. #19155

Merged
merged 8 commits into from
May 11, 2017
Merged

Conversation

taylorotwell
Copy link
Member

This is a slightly different approach to use custom validation objects
compared to the current Validator::extend approach. With this addition,
you can define an object that implements
Illuminate\Validation\ValidationRule and then include it in your
validation rules like so: 'name' => [new ValidName].

This provides a quick way to define custom validation rules without
needing to call Validator::extend at all.

This is a slightly different approach to use custom validation objects
compared to the current Validator::extend approach. With this addition,
you can define an object that implements
Illuminate\Validation\ValidationRule and then include it in your
validation rules like so: ‘name’ => [new ValidName].

This provides a quick way to define custom validation rules without
needing to call Validator::extend at all.
@tillkruss tillkruss changed the title Support custom validation rule objects. [5.5] Support custom validation rule objects. May 11, 2017
@taylorotwell taylorotwell merged commit 6704b2a into master May 11, 2017
@taylorotwell taylorotwell deleted the validation-rules branch May 11, 2017 20:05
},
'name' => function ($attribute, $value, $fail) {
if ($value !== 'taylor') {
$fail(':attribute must be taylor');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What kind of type it is? I mean $fail

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

method

@ghost
Copy link

ghost commented Oct 5, 2017

Is it possible to overwrite the validation message specified in the Rule with a custom message in the FormRequest?

@amadeann
Copy link
Contributor

amadeann commented Jan 7, 2018

@skatika Yes. Here's what worked for me:

Added code like this to the withValidator method of my FormRequest:

$validator->addRules([
    'status' => function ($attribute, $value, $fail) {
        if ( $attribute < 10 ) {
            $fail(':attribute must be at least 10 for the validation to pass');
        }
    }
]);

If you're using classes instead of closures, change it to:

$validator->addRules([
    'status' => [new YourCustomRule]
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants