DEV Community

Cover image for Creating Custom Validation Rules in Laravel
Raymond Baghumian
Raymond Baghumian

Posted on

Creating Custom Validation Rules in Laravel

by default we using request laravel which validates user input data.

but we want Create Custom Validation rules which by default request validation we don't use.

with under command create two file ValiMobile and ValiPassword:

php artisan make:rule ValidMobile
php artisan make:rule ValidPassword
Enter fullscreen mode Exit fullscreen mode

I got for Regex from site under helping.

https://ihateregex.io/
Enter fullscreen mode Exit fullscreen mode

Code VailMobile :

class ValidMobile implements ValidationRule
{
    public function __construct()
    {
        //
    }
    public function passes($attribute, $value): bool|int
    {
        return preg_match('/^9[0-9]{9}$/', $value);
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!preg_match('/^9[0-9]{9}$/', $value)) {
            $fail('Your ' . $attribute . 'number is 10 digits and enter without zero.');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code VailPassword :

class ValidPassword implements ValidationRule
{
    public function __construct()
    {
        //
    }
    public function passes($attribute, $value): bool|int
    {
        return preg_match('/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$ %^&*-]).{8,}$/', $value);
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!preg_match('/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$ %^&*-]).{8,}$/', $value)) {
            $fail('The type of'  . $attribute .  'is inappropriate and must be a combination of uppercase, lowercase letters and numbers.');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

at the end Calling Two File VailMobile and VailPassword:

use App\Rules\ValidMobile;
use App\Rules\ValidPassword;

return Validator::make($data,
   [
      'mobile' => ['nullable', 'string', 'unique:users', new ValidMobile()],
      'password' => ['required', 'string', 'confirmed', new ValidPassword()],
   ]
);
Enter fullscreen mode Exit fullscreen mode

Good luck :)

Top comments (0)