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.
CodePudding user response:
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',
]);