Laravel中正则规则的自定义验证消息?

时间:2013-12-02 02:57:26

标签: php validation 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.'
)

这些都没有奏效。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:9)

我能够通过使用这种方法来解决这个问题:

'custom' => array(
    'password' => array(
        'regex' => 'Password must contain at least one number and both uppercase and lowercase letters.'
    )
)

但我很想知道为什么其他任何一种方法如果有人碰巧知道其他方法都没有用??

答案 1 :(得分:0)

好象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 );