1
votes

I'm having difficulty figuring out how to write a custom validation rule in Laravel 5.1. I've read the documentation, but it seems incomplete. Looking it over, I just don't see where I'm supposed to put my actual validation logic, such as if (stristr($string, 'test')) { ... and so on.

For another thing, it doesn't show in what method/array the error message defintions should go:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

My actual use case is somewhat strange, so for this question, let's use the example of validating a secure password. A secure password must be at least 8 characters long, containing a lowercase and uppercase letter, a number and a special character.

Actually, that's a pretty tall order for an example, so how about just checking for a number? Or running any string function on the value?

How would one create such a validation rule?

1
Have you checked this links - laravel.com/docs/5.1/validation#custom-validation-rules ? it's quite easier to add new custom validation - Jobayer
@Jobayer I literally linked that in my question. - user151841
I think if someone want to validate with something not in the form will struggle with this. I'm looking for the answer as well. - ClearBoth
I figure it out using "Manually Creating Validators" with After Validation Hook - ClearBoth

1 Answers

-1
votes

As described in the document you've linked, you need to put your validation logic inside the boot function of a ServiceProvider, (e.g. AppServiceProvider) by using the static extend method.

Here is a short example (associated with the example in the docs).

<?php

namespace App\Providers;

use Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('yourFunctionNameHere', function($attribute, $value, $parameters, $validator) {
            return $value == 'yourTestValueHere'; //change the body as you need it
        });
    }
} 

The input of the user is assigned to $value