Fokrule
Fokrule

Reputation: 854

Regular Expression is not working properly in laravel validation

I am using laravel validation. I want to take input and store data like this. 111-111-111. This is the demo value. There should be 3 number in each part. Here is my validation rule

'id'  => 'required|regex:/[0-9]{3}-[0-9]{3}-[0-9]{3}/|unique:info',

First two part working perfect but in last part I can take more than 3 number. I mean if input is 111-111-11111 it take the input.

Upvotes: 1

Views: 1592

Answers (1)

lewis4u
lewis4u

Reputation: 15037

That is normal. You need to think about regex like a search engine. With your rule, you actually say:

Is there a string that has 3 numbers and then a hyphen (-)
                           3 numbers and then a hyphen (-)
                           3 numbers

So this is true:

123-112-111

But also this is true:

111-111-111111111
145-156-1155
123-456-87897

Because all of them have the 3 numbers and hyphen, 3 numbers and hyphen, 3 numbers and hyphen!

You need to limit your input differently. Maybe with another rule in controller, for example:

'id'  => 'required|regex:/[0-9]{3}-[0-9]{3}-[0-9]{3}/|max:11|unique:info',

This was just a basic example, I am sure you can figure out something even better.

Also check this website: https://regexr.com/


Update

This is actually the best solution for your problem:

/[0-9]{3}-[0-9]{3}-[0-9]{3}$/

With $ at the end of your regex you say:

This is the end of my string, don't accept the input if user writes more than 3 characters after second hyphen.

Upvotes: 2

Related Questions