12

Pretty basic question, I'm trying to customise the error message for a regex validation rule in Laravel. The particular rule is for passwords and requires the password to have 6-20 characters, at least one number and an uppercase and lowercase letter so I'd like to communicate this to the user rather than just the default message which says the format is "invalid".

So I tried to add the message into the lang file in a few different ways:

1)

'custom' => array(
    'password.regex:' => 'Password must contain at least one number and both uppercase and lowercase letters.'
)

2)

'custom' => array(
    'password.regex' => 'Password must contain at least one number and both uppercase and lowercase letters.'
)

3)

'custom' => array(
    'password.regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})' => 'Password must contain at least one number and both uppercase and lowercase letters.'
)

None of these have worked. Is there a way to do this?

Nick Coad
  • 3,623
  • 4
  • 30
  • 63

2 Answers2

15

I was able to solve this by using this method instead:

'custom' => array(
    'password' => array(
        'regex' => 'Password must contain at least one number and both uppercase and lowercase letters.'
    )
)

but I'd love to know why one of the other methods didn't work if anyone happens to know...?

Nick Coad
  • 3,623
  • 4
  • 30
  • 63
  • thanks for sharing but let me know where you had been made custom validation? in controller or request file? – fahdshaykh Nov 10 '21 at 12:32
3

Well seems like laravel 7 solves this:

        $messages = [
            'email.required' => 'We need to know your e-mail address!',
            'password.required' => 'How will you log in?',
            'password.confirmed' => 'Passwords must match...',
            'password.regex' => 'Regex!'
        ];
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => [
                'required',
                'string',
                'min:7',
                'confirmed',
                'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/'
            ]
        ];
        return Validator::make($data, $rules, $messages );
Phil.Ng
  • 116
  • 8