Home » Php » php – Custom validation message for regex rule in Laravel?

php – Custom validation message for regex rule in Laravel?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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…?

Answer:

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 );