【问题标题】:Issue with Laravel Rules & Regex (OR) operatorLaravel 规则和正则表达式 (OR) 运算符的问题
【发布时间】:2014-05-01 01:16:42
【问题描述】:

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

);

【问题讨论】:

标签: php regex laravel


【解决方案1】:

我用这种风格救了我的命:-)

修改代码

    $validator = Validator::make(
    $request->all(),
        [
        'name' => 'required|string',
        'initial_credit' => 'required|integer|between:0,1000000|regex:/[1-9][0-9]*0000$/'
        ]
    ]);

    $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
    ]);

【讨论】:

    【解决方案2】:

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

    正则表达式:模式

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

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

    澄清: 你会做这样的事情

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

    【讨论】:

    • 我检查过了,但我不太确定这是什么意思,那么规则已经在一个数组中:public static $rules = array('name'=>'required|regex:/^(( Comp)|(Soen)|(Engr)|(Elec))/i', 'cid'=>'required|regex:/^((comp)|(soen)|(engr)|(elec))\d {3}$/i', 'credits'=>'required|numeric' );
    • 编辑了我的答案以阐明如何使用数组。
    • 在多个验证规则(包括正则表达式)中苦苦挣扎了大约一个小时,这救了我。
    【解决方案3】:

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

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

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

    【讨论】:

    • 嗨,我尝试了上面的代码,但出现错误(主帖中的完整代码):BadMethodCallException 方法 [validateRequired|regex] 不存在。
    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2013-11-18
    • 2014-08-24
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多