Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active January 8, 2025 18:31
Show Gist options
  • Save EduardoSP6/13ff5c8d21e50e646612296fdf128d22 to your computer and use it in GitHub Desktop.
Save EduardoSP6/13ff5c8d21e50e646612296fdf128d22 to your computer and use it in GitHub Desktop.
Custom password validation laravel 7

Custom password validation laravel 7:

For create a custom password rule for laravel you should run a command: php artisan make:rule PasswordRule. The class will be created in App\Rules folder.

Example:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class PasswordRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strlen($value) >= 8
            && preg_match('/[a-z]/', $value) == 1
            && preg_match('/[A-Z]/', $value) == 1
            && preg_match('/[0-9]/', $value) == 1
            && preg_match('/[&"%$#@+-]/', $value) == 1;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The password field must contain at least 8 characters, 1 uppercase letter, 1 lowercase letter '.
            'and one of the symbols &"%$#@+-';
    }
}

Now you can implement this rule in request validator of your user CRUD.

For example:

<?php

namespace App\Http\Requests;

use App\Rules\PasswordRule;
use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    
    public function rules() {
      switch ($this->method()) {
        case 'POST': {
          return [
              'name' => 'required|string',
              'email' => 'required|email|unique:users',
              'password' => ['required', 'string', new PasswordRule()],        
          ];
        }
      }
    }
}

Or using Validator class:

$data = $request->all();

$validator = Validator::make($data, [
    'password' => [
        'required',
        'string',
        new PasswordRule()
    ]
]);

Including you can implement in ResetPasswordController for validation in rules method.

Example:

class ResetPasswordController extends Controller {
 
     /**
     * Get the password reset validation rules.
     *
     * @return array
     */
    protected function rules()
    {
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => ['required', 'confirmed', new PasswordRule()],
        ];
    }
}    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment