3

so I have validated a password with different regex pattern, now I want to return different validation messages for each pattern so that user can get a exact error message, I don't want to return one message for all patterns.

so whatever I've tried so far is as below

        $request->validate([
            'password'=>[
                'required',
                'min:8',
                'string',
                'regex:/[a-z]/',
                'regex:/[A-Z]/',
                'regex:/[0-9]/',
                'regex:/[@$!%*#?&]/', //required special chars
                'not_regex:/^(20|19|0)/', //must not start with 20 or 19 or 0
                'not_regex:/(.)\1{1}/', //doubles are not allowed
                'not_regex:/(123(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?|234(?:5(?:6(?:7(?:89?)?)?)?)?|345(?:6(?:7(?:89?)?)?)?|456(?:7(?:89?)?)?|567(?:89?)?|6789?|789)/', //sequential number must not be more than 2
            ]
        ],[
            'password.regex.0'=>'password must contain a lower case character',
            'password.regex.1'=>'password must contain an upper case character',
        ]);

but the custom message is not working for regex patterns, its only returning common message "The password format is invalid." is there any ideal way to do that?

NB: I have checked all the stack overflow questions but got no solutions, My validation works fine just need to return specific error message for each pattern.

1 Answer 1

4

You can create either a custom validation rule for each regex with an appropriate message in each, or you could use an inline closure.

$request->validate([
            'password'=>[
                'required',
                'min:8',
                'string',
                function ($attribute, $value, $fail) {
                    if (!preg_match(“/[@$!%*#?&]/“, $value)) {
                        $fail('You must include a special character.');
                    }
                },
                // ...
            ]
        ],[
            'password.regex.0'=>'password must contain a lower case character',
            'password.regex.1'=>'password must contain an upper case character',
        ]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it works like a charm, but I had to wrap the pattern with string like !preg_match("/[@$!%*#?&]/", $value), I think you should add it to avoid syntax errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.