1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

it worked fine.thank you so much. But still I am confused why my condition is not working.Because I have set three number for last part. then why more than three number it is accepting. can you please explain me if you can.
Because it matches your rule...It doesn't limit it...It's like when you search something on the Internet or on your OS. When you type and search for: controller that word matches also all the words that have controller inside. So UsersController is a match, ItemsController is a match... Same thing with your regex rule. It matches no mather how many numbers you write at the end.
No problem. Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.