php Laravel 规则和正则表达式 (OR) 运算符的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22596587/
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
Issue with Laravel Rules & Regex (OR) operator
提问by Jimmy
I'm having a small issue with my Laravel rules and regex operation :
我的 Laravel 规则和正则表达式操作有一个小问题:
Basically a rule is an array as such :
基本上规则是这样的数组:
'room'=>'required|alpha_num|min:2|max:10',
The problem i'm having is when using regex and the | (or) operator such as :
我遇到的问题是使用正则表达式和 | (或)运算符,例如:
'cid'=>'required|regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i',
I'm getting a server error saying :
我收到服务器错误消息:
ErrorException
preg_match(): No ending delimiter '/' found
I'm guessing the preg_match
is stopping at the first |
inside the /.../
.
我猜preg_match
是停在第一个|
里面/.../
。
Is there anyway to write the above code to make it work ?
有没有写上面的代码来使它工作?
Full code :
完整代码:
public static $rules = array(
'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i'),
'description'=>'required|regex:/^[A-Za-z \t]*$/i|min:3|unique:courses',
'credits'=>'required|regex:/^\d+(\.\d)?$/'
);
回答by stoppert
http://laravel.com/docs/validation#rule-regex
http://laravel.com/docs/validation#rule-regex
regex:pattern
The field under validation must match the given regular expression.
Note:When using the regex pattern, it may be necessary to specify rules in an array instead >of using pipe delimiters, especially if the regular expression contains a pipe character.
正则表达式:模式
验证字段必须与给定的正则表达式匹配。
注意:使用正则表达式模式时,可能需要在数组中指定规则而不是 > 使用管道分隔符,尤其是当正则表达式包含管道字符时。
To clarify: You would do something like this
澄清:你会做这样的事情
$rules = array('test' => array('size:5', 'regex:foo'));
回答by The Alpha
You should use an array
instead of separating rules using |
:
您应该使用array
代替 分隔规则|
:
'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i')
The pipe (|
) sigh is available in your regular expression pattern so it's conflicting with the separator. Other answer already stated it.
管道 ( |
) 叹气在您的正则表达式模式中可用,因此它与分隔符冲突。其他答案已经说明了。
回答by Ali Yousefi
I use this style and save my life :-)
我使用这种风格并挽救了我的生命:-)
change code from
更改代码
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string',
'initial_credit' => 'required|integer|between:0,1000000|regex:/[1-9][0-9]*0000$/'
]
]);
to
到
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string',
'initial_credit' => [ // <=== Convert To Array
'required',
'integer',
'between:0,1000000',
'regex:/([1-9][0-9]*0000$)|([0])/' // <=== Use pipe | in regex
] // <=== End Array
]);