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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20320148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:43:27  来源:igfitidea点击:

Custom validation message for regex rule in Laravel?

phpvalidationlaravel

提问by Nick Coad

Pretty basic question, I'm trying to customise the error message for a regex validation rule in Laravel. The particular rule is for passwords and requires the password to have 6-20 characters, at least one number and an uppercase and lowercase letter so I'd like to communicate this to the user rather than just the default message which says the format is "invalid".

非常基本的问题,我正在尝试为 Laravel 中的正则表达式验证规则自定义错误消息。特定规则适用于密码,要求密码包含 6-20 个字符,至少有一个数字和一个大写和小写字母,因此我想将此信息传达给用户,而不仅仅是默认的消息,该消息表示格式为“无效的”。

So I tried to add the message into the lang file in a few different ways:

所以我尝试以几种不同的方式将消息添加到 lang 文件中:

1)

1)

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

2)

2)

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

3)

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.'
)

None of these have worked. Is there a way to do this?

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

回答by Nick Coad

I was able to solve this by using this method instead:

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

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

but I'd love to know why one of the other methods didn't work if anyone happens to know...?

但我很想知道如果有人碰巧知道为什么其他方法之一不起作用......?

回答by Phil.Ng

Well seems like laravel 7 solves this:

好吧,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 );