php Laravel 5.2 中的正则表达式验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34804290/
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
Regex Validation in Laravel 5.2
提问by Pankaj
Below is my rule for password:
以下是我的密码规则:
return [
'Password' => 'required|min:8|max:100|regex:[a-z{1}[A-Z]{1}[0-9]{1}]',
'Password_confirmation' => 'required|min:8|max:100|regex:[a-z{1}[A-Z]{1}[0-9]{1}]',
];
I am trying to add the rule such that it must have
我正在尝试添加规则,使其必须具有
- atleast one small char
- atleast one big char
- atleast one number
- atleast one special char
- min 8 chars
- 至少一个小字符
- 至少一个大字符
- 至少一个数字
- 至少一个特殊字符
- 最少 8 个字符
I tried this and it works required|confirmed|min:8|max:100|regex:/^[\w]{1,}[\W]{1,}$/, on a regex tester software. but not sure why it does not work in Laravel
我required|confirmed|min:8|max:100|regex:/^[\w]{1,}[\W]{1,}$/在正则表达式测试器软件上尝试了这个,它可以工作。但不确定为什么它在Laravel中不起作用
Am I missing something ?
我错过了什么吗?
回答by Mike Rockétt
Use:
用:
return [
'password' => [
'required',
'confirmed',
'min:8',
'max:50',
'regex:/^(?=.*[a-z|A-Z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/',
]
];
Firstly, you do not need to check the confirmation separately. Just use the confirmedrule.
首先,您不需要单独检查确认。只需使用confirmed规则。
The expression you were using was invalid, and had nothing to do with what you wanted. I do suggest you do some researchon regular expressions.
您使用的表达式无效,与您想要的无关。我建议你对正则表达式做一些研究。
Due to the fact that the expression shown above uses pipes (|), you can specify the rules using an array.
由于上面显示的表达式使用管道 ( |),您可以使用数组指定规则。
Edit:You could also use this expression, which appears to have been tested a little more thoroughly.
编辑:您也可以使用这个表达式,它似乎已经过更彻底的测试。
/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/
回答by Bogdan
You might want to check the PasswordStrengthPackage. It registers new validation rules that do what you need and are much more readable than a regular expression. So in your case you can have this:
您可能需要检查PasswordStrengthPackage。它注册了新的验证规则,可以满足您的需求,并且比正则表达式更具可读性。所以在你的情况下,你可以有这个:
return [
'Password' => 'required|min:8|max:100|case_diff|numbers|letters|symbols|confirmed'
];
The Password_confirmationrule is not needed as long as the confirmation value is present and you add the confirmedrule for the Passwordfield.
在Password_confirmation只要确认值存在,并且您添加不需要的规则confirmed统治的Password领域。

