Laravel Rules & Regex (OR) 运算符的问题

2022-08-30 21:45:12

我在我的Laravel规则和正则表达式操作中遇到了一个小问题:

基本上,规则是这样的数组:

'room'=>'required|alpha_num|min:2|max:10',

我遇到的问题是使用正则表达式和|(或)运算符,例如:

'cid'=>'required|regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i',

我收到一个服务器错误,说:

ErrorException

preg_match(): No ending delimiter '/' found

我猜是停在里面的第一个.preg_match|/.../

无论如何,有没有编写上面的代码来使其工作?

完整代码 :

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)?$/'

);

答案 1

http://laravel.com/docs/validation#rule-regex

正则表达式:模式

正在验证的字段必须与给定的正则表达式匹配。

注意:使用正则表达式模式时,可能需要在数组中指定规则,而不是使用管道分隔符>,尤其是在正则表达式包含管道字符时。

澄清一下:你会做这样的事情

$rules = array('test' => array('size:5', 'regex:foo'));

答案 2

您应该使用 而不是使用 分隔规则:array|

'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i')

管道 () 叹息在正则表达式模式中可用,因此它与分隔符冲突。其他答案已经说过了。|


推荐