[英]Custom validation message for regex rule in Laravel?
非常基本的問題,我正在嘗試為 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 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.