Fateh Alrabeai
Fateh Alrabeai

Reputation: 730

How to validate phone number in laravel?

I want to validate the field of phone number and allow only numbers that start with the following digits 77, 71 , 73 .

How can I implement that in the request that I created?

public function rules()
    {
        return [
            'name'=>'required',
            'password'=>'required|min:6',
            'phone'=>'required|digits:9',
        ];
    }

Upvotes: 3

Views: 18138

Answers (4)

Sirjiskit
Sirjiskit

Reputation: 669

The other answers given are excellent but it depends on the country used as phones varies from country to country for example in Nigeria we validate phone number like

public function rules()
    {
        return [
            'name'=>'required',
            'password'=>'required|min:6',
            'phone'=>'required|regex:/^(080|091|090|070|081)+[0-9]{8}$/',
        ];
    }

Upvotes: 0

Ali Sharifi Neyestani
Ali Sharifi Neyestani

Reputation: 4388

One possible solution would to use regex.

 'phone' => ['required', 'regex:/^((71)|(73)|(77))[0-9]{7}/']
  1. I assume your phone number has 9 digits so I used {7} // (71|73|77)2 digits + 7 digits = 9 digits
  2. Notice when you want to use OR, you should use an array instead of separating rules using |

Upvotes: 3

STA
STA

Reputation: 34668

You can use regex to validate a phone number like :

'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.

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520938

You should just a regex solution here, e.g.

var numbers = [771234567, 128675309];
console.log(/^(?:71|73|77)\d{7}$/.test(numbers[0]));
console.log(/^(?:71|73|77)\d{7}$/.test(numbers[1]));

Upvotes: 2

Related Questions