Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation message for regex rule in Laravel?

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?

like image 889
Nick Coad Avatar asked Dec 02 '13 02:12

Nick Coad


1 Answers

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 );
like image 106
Phil.Ng Avatar answered Oct 21 '22 13:10

Phil.Ng