Laravel 5.4 - Validation with Regex [duplicate]
Asked Answered
P

1

50

Below is my rule for project name:

$this->validate(request(), [
    'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];

I am trying to add the rule such that it must start with a letter from a-z or A-z and can end with numbers but most not.

Valid values for project name:

myproject123
myproject
MyProject

Invalid values for project name:

123myproject
!myproject
myproject 123
my project
my project123

I tried my regex online:

enter image description here

https://regex101.com/r/FylFY1/2

It should work, but I can pass the validation even with project 123.

UPDATE: It actually works, I just tested it in the wrong controller, im sorry... but maybe it will help others nevertheless

Pollinate answered 3/3, 2017 at 10:57 Comment(0)
L
91

Your rule is well done BUT you need to know, specify validation rules with regex separated by pipeline can lead to undesired behavior.

The proper way to define a validation rule should be:

$this->validate(request(), [
    'projectName' => 
        array(
            'required',
            'regex:/(^([a-zA-Z]+)(\d+)?$)/u'
        )
]);

You can read on the official docs:

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

Lipase answered 3/3, 2017 at 11:8 Comment(3)
ups. my variant actually works too, I just tested it on the wrong controller :/Pollinate
With Laravel 5.5+ you can invoke $request->validate(['field1'=>'required|regex:/foo/u']);`.Egwan
have you miss brace ')'Fixative

© 2022 - 2024 — McMap. All rights reserved.