这是一个非常基本的问题,我正在尝试在Laravel中为正则表达式验证规则自定义错误消息。特定规则适用于密码,要求密码包含6-20个字符,至少一个数字和一个大小写字母,所以我想将此信息传达给用户,而不仅仅是默认消息,即格式"无效"。
因此,我尝试以几种不同的方式将消息添加到lang文件中:
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.'
)
这些都没有奏效。有办法做到这一点吗?
我可以通过使用以下方法来解决这个问题:
'custom' => array(
'password' => array(
'regex' => 'Password must contain at least one number and both uppercase and lowercase letters.'
)
)
但我很想知道,如果有人碰巧知道,为什么其他方法之一不起作用。。。?
看起来laravel 7解决了这个问题:
$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 );