php - 每个正则表达式模式的 laravel 自定义验证错误

标签 php regex validation laravel-7

所以我已经使用不同的正则表达式模式验证了密码,现在我想为每个模式返回不同的验证消息,以便用户可以获得准确的错误消息,我不想为所有模式返回一条消息。

所以到目前为止我尝试过的内容如下

        $request->validate([
            'password'=>[
                'required',
                'min:8',
                'string',
                'regex:/[a-z]/',
                'regex:/[A-Z]/',
                'regex:/[0-9]/',
                'regex:/[@$!%*#?&]/', //required special chars
                'not_regex:/^(20|19|0)/', //must not start with 20 or 19 or 0
                'not_regex:/(.)\1{1}/', //doubles are not allowed
                'not_regex:/(123(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?|234(?:5(?:6(?:7(?:89?)?)?)?)?|345(?:6(?:7(?:89?)?)?)?|456(?:7(?:89?)?)?|567(?:89?)?|6789?|789)/', //sequential number must not be more than 2
            ]
        ],[
            'password.regex.0'=>'password must contain a lower case character',
            'password.regex.1'=>'password must contain an upper case character',
        ]);

但自定义消息不适用于正则表达式模式,它仅返回常见消息“密码格式无效”。有什么理想的方法可以做到这一点吗?

NB: I have checked all the stack overflow questions but got no solutions, My validation works fine just need to return specific error message for each pattern.

最佳答案

您可以创建 custom validation rule对于每个正则表达式,每个正则表达式都有适当的消息,或者您可以使用 inline closure .

$request->validate([
            'password'=>[
                'required',
                'min:8',
                'string',
                function ($attribute, $value, $fail) {
                    if (!preg_match(“/[@$!%*#?&]/“, $value)) {
                        $fail('You must include a special character.');
                    }
                },
                // ...
            ]
        ],[
            'password.regex.0'=>'password must contain a lower case character',
            'password.regex.1'=>'password must contain an upper case character',
        ]);

关于php - 每个正则表达式模式的 laravel 自定义验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73729679/

相关文章:

php - PHP 和 SQL 中的单元测试

java - 对于所有相同的号码,电话号码验证应该失败

Java:String.replace(regex, string) 从 XML 中删除内容

wpf mvvm 错误验证

javascript - 如何使用XAMPP本地服务器获取JSON/JSONP数据?

php - 从数据库中阻止 .htaccess 或 PHP 中的 IP 地址?

PHP 未使用准备好的语句从 mysql 选择任何值

php - 在 PHP 中使用正则表达式查找并替换 "["和,或 "]"

asp.net-mvc - 使用 ASP.NET MVC 3 本地化非数据注释错误的最佳方法是什么?

c# - 如果表单未通过验证,密码字段是否应保留其值?