简体   繁体   中英

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',
        ];
    }

You should just a regex solution here, eg

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

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.

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 |

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}$/',
        ];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM