0

for laravel 5 i want to create and define custom validator, but i can't find whitch file and folder i must be register that, i can not find that in laravel documents, for example after create Extension\Validation folders into app folder, i'm create this class:

<?php
namespace App\Extension\Validation;
use Illuminate\Validation\Validator;
class CustomValidator extends Validator {

    public function validateNationalCode ($attribute, $value, $parameters)
    {
        if (!preg_match('/^[0-9]{10}$/', $value)) {
            return false;
        }
        for ($i = 0; $i < 10; $i++) {
            if (preg_match('/^' . $i . '{10}$/', $value)) {
                return false;
            }
        }

        for ($i = 0, $sum = 0; $i < 9; $i++) {
            $sum += ((10 - $i) * intval(substr($value, $i, 1)));
        }
        $ret = $sum % 11;
        $parity = intval(substr($value, 9, 1));

        if (($ret < 2 && $ret == $parity) || ($ret >= 2 && $ret == 11 - $parity)) {
            return true;
        }

        return false;
    }
}

now i must be use below code to register that :

Validator::resolver(function($translator, $data, $rules, $messages)
{
    return new CustomValidator($translator, $data, $rules, $messages);
});

Laravel Document:

Registering A Custom Validator Resolver Next, you need to register your custom Validator extension:

which file i must be add or append?

1 Answer 1

1

First go to /app/providers/appServiceProviders.php then use validator on your class

use Validator;

then write your custom validation in boot method,like this

public function boot()
{
    Validator::extend('alpha_dash_spaces', function($attribute, $value, $parameters) {
        return (bool) preg_match( "/^[A-Za-z\s-_]+$/", $value );
    });
}

Then go /resources/land/en/validator.php and write your custom validation messages like this

'alpha_num_spaces'     => 'The :attribute may only contain letters, numbers, and spaces.',
Sign up to request clarification or add additional context in comments.

2 Comments

i get this error: [Symfony\Component\Debug\Exception\FatalErrorException] Class 'App\Providers\Validator' not found
@mahdipishguy i edited code to use validator class,please try again

Your Answer

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