Issue with Laravel Rules & Regex (OR) operator

前端 未结 3 1454
悲哀的现实
悲哀的现实 2020-11-28 15:34

I\'m having a small issue with my Laravel rules and regex operation :

Basically a rule is an array as such :

\'room\'=>\'required|alpha_num|min:2|         


        
相关标签:
3条回答
  • 2020-11-28 16:14

    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'));
    
    0 讨论(0)
  • 2020-11-28 16:21

    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
        ]);
    
    0 讨论(0)
  • 2020-11-28 16:33

    You should use an array instead of separating rules using |:

    '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.

    0 讨论(0)
提交回复
热议问题