【问题标题】:Custom validation message for regex rule in Laravel?Laravel 中正则表达式规则的自定义验证消息?
【发布时间】:2013-12-17 16:19:23
【问题描述】:

非常基本的问题,我正在尝试为 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.'
)

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

【问题讨论】:

    标签: php validation laravel


    【解决方案1】:

    我可以改用这个方法来解决这个问题:

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

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

    【讨论】:

    • 感谢分享,但请告诉我您在哪里进行了自定义验证?在控制器或请求文件中?
    【解决方案2】:

    看来 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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 2013-10-17
      • 2015-09-07
      • 2021-08-30
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多