72

I want to validate user input phone number where number should be exactly 11 and started with 01 and value field should be number only. How do I do it using Laravel validation?

Here is my controller:

  public function saveUser(Request $request){
        $this->validate($request,[
            'name' => 'required|max:120',
            'email' => 'required|email|unique:users',
            'phone' => 'required|min:11|numeric',
            'course_id'=>'required'
            ]);

        $user = new User();
        $user->name=  $request->Input(['name']);
        $user->email=  $request->Input(['email']);
        $user->phone=  $request->Input(['phone']);
        $user->date = date('Y-m-d');
        $user->completed_status = '0';
        $user->course_id=$request->Input(['course_id']);
        $user->save();
       return redirect('success');

    }
User57
  • 2,453
  • 14
  • 36
  • 72
  • I hope this will help your [php - Custom Validate Phone numbers in Laravel 4.2 - Stack Overflow](http://stackoverflow.com/questions/29259366/custom-validate-phone-numbers-in-laravel-4-2?answertab=votes#tab-top) It say's 4.2 but this method is also available in 5.2 – Devsome Apr 21 '16 at 18:44
  • 1
    What is the problem you are getting with this code? – Abhishek Apr 22 '16 at 14:31
  • If the phone number to be validated should always "be exactly 11", why did you use a input field for this? – Nico Haase Feb 11 '20 at 13:09

9 Answers9

143

One possible solution would to use regex.

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

This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numeric or size validation rules.

If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.

Docs: Custom Validation

In your AppServiceProvider's boot method:

Validator::extend('phone_number', function($attribute, $value, $parameters)
{
    return substr($value, 0, 2) == '01';
});

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.

Yat23
  • 181
  • 4
SlateEntropy
  • 3,988
  • 1
  • 23
  • 31
  • 6
    Your regex is not perfect. It doesn't match from the start and it doesn't check for length, so this is also valid: `ht01123456789123456789`. This is the correct regex (as a validation rule): `'regex:/^(\+36)[0-9]{9}$/'`. – totymedli Apr 08 '17 at 10:40
  • 2
    If you write a phone number validator, it should validate every requirement a phone number must fulfill. It should also check for length and numerical values. In your current solution you need to add other rules everywhere you use it. Although it works, it isn't a well organized solution. The validator isn't complete, after the validation passes - despite its name - it doesn't tell if something is really a phone number, only that it starts with `01`. – totymedli Apr 08 '17 at 10:55
  • 1
    This is no longer valid. In the Netherlands, M2M numbers have been introduced that are 12 digits long. – FrozenDroid Jan 03 '18 at 12:50
  • you can try this as well, to select any country code with plus sign along with dash: /\+([0-9][0-9])(\-)[0-9]{9}$/ , know that its input must be: +xx-xxxxxxxxx – Sabaoon Bedar May 17 '21 at 09:28
72

From Laravel 5.5 on you can use an artisan command to create a new Rule which you can code regarding your requirements to decide whether it passes or fail.

Ej: php artisan make:rule PhoneNumber

Then edit app/Rules/PhoneNumber.php, on method passes

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{

    return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
}

Then, use this Rule as you usually would do with the validation:

use App\Rules\PhoneNumber;

$request->validate([
    'name' => ['required', new PhoneNumber],
]);

docs

javier_domenech
  • 5,995
  • 6
  • 37
  • 59
32
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
        return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
    });

Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
        return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
    });

Usage

Insert this code in the app/Providers/AppServiceProvider.php to be booted up with your application.

This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone validation rule anywhere in your application, so your form validation could be:

 'phone' => 'required|numeric|phone' 
Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31
Nady Shalaby
  • 604
  • 7
  • 7
  • 8
    Thanks! To anyone having trouble with this, be sure to add `use Illuminate\Support\Facades\Validator` to the top of `AppServiceProvider` – fronzee Jan 05 '17 at 18:00
  • 2
    This should be the more accepted answer as it is more thorough than the one chosen. Then again I understand that the time at which this answer was given makes all the difference. – Andre F. Feb 11 '17 at 15:45
  • when the phone number is not mandatory, this solution keep throwing error message "phone is invalid phone number" – Wildan Muhlis Dec 06 '17 at 23:48
20

You can use this :

        'mobile_number' => ['required', 'digits:10'],
12

Use required|numeric|size:11 Instead of required|min:11|numeric

Abhishek
  • 3,900
  • 21
  • 42
12

You can try out this phone validator package. Laravel Phone

Update

I recently discovered another package Lavarel Phone Validator (stuyam/laravel-phone-validator), that uses the free Twilio phone lookup service

aphoe
  • 2,586
  • 1
  • 27
  • 31
1

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

Community
  • 1
  • 1
ShaneMit
  • 171
  • 1
  • 7
-2

I used the code below, and it works

'PHONE' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',
TAbdiukov
  • 1,185
  • 3
  • 12
  • 25
-7
$request->validate([
    'phone' => 'numeric|required',
    'body' => 'required',
]);