3

How would I go about validating a number in laravel.

I need the number stored in the following format 353861111111.

353 will be the prefix, and the user types in the rest. If the user types in 086, this is invalid.

2
  • Is that a typo or the number is supposed to be 12 digits? Commented Sep 6, 2018 at 20:18
  • I updated my answer, I believe that is regex you are looking for. Commented Sep 6, 2018 at 21:15

3 Answers 3

5

You can use regex as:

'phone' => 'required|regex:/(353)[0-9]{9}/'

This checks for the pattern with starting with 353 followed by 9 digits having values from 0-9.

Or you can build a custom validator in boot method of AppServiceProvider.php:

Validator::extend('phone_number', function($attribute, $value, $parameters)

    {
        return substr($value, 0, 3) == '353';
    });

This will allow you to use the phone_number validation rule anywhere in your application, so your form validation could be:

'phone' => 'required|numeric|phone_number|size:11'

In your validator extension you could also check if the $value is numeric and 11 characters long.

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

Comments

2

Here is how I did it on an older Laravel 4 project we have to update from time to time:

'phone' => 'required|regex:/^\d{3}-\d{3}-\d{4}$/',

Comments

0

Try this regex expression:

'number' => 'required|regex:^[3][5][3][\d]{8}[\d]$'

6 Comments

This regex is completely wrong. Eg it matches 333000000000 - wrong prefix, wrong number of characters. regex101.com/r/L3YBKV/1
@Don'tPanic I updated the regex. Allows only 12 integers and the first three must be 353.
No, still quite wrong. Did you test it? [353] is a character class, and it means match any of those characters - so 333 still matches, or 555 or 355, etc. [\d] is meaningless - a character class of a decimal number is the same as just a decimal number, or \d. And why specify 8 decimals followed by a decimal? You have a lot to learn about regexs, grasshopper :-)
@Don'tPanic Okay, I edited it again. Tested it, think it works well now.
If you want to match exactly 353, there is no need to make patterns of the digits - that is pointless work for the matching engine. 353 is all you need. Other problems I described last time are still there. How about simply ^353\d{9}$?
|

Your Answer

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