Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Laravel Rules & Regex (OR) operator

Tags:

regex

php

laravel

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

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

);
like image 812
Jimmy Avatar asked Mar 23 '14 20:03

Jimmy


People also ask

What is rule in laravel?

In Laravel, there are Validation Rules which are predefined rules, which when used in Laravel application. There is a list of rules that can be used to validate the data being submitted by the user. Laravel Form with Validation Rules and Default Error Messages. Syntax 1: Basic validation rules.

Which method is used to check validation error in laravel?

After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.


2 Answers

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'));
like image 77
stoppert Avatar answered Sep 20 '22 17:09

stoppert


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.

like image 28
The Alpha Avatar answered Sep 19 '22 17:09

The Alpha