Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate phone number in laravel 5.2? [closed]

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');      } 
like image 515
User57 Avatar asked Apr 21 '16 18:04

User57


People also ask

How can I verify my phone number in laravel?

Validate Phone Number Laravel public function save(Request $request) { $validated = $request->validate([ phone_number=> 'required|numeric|min:10' ]); //If number passes validation, method will continue here. } In our save function we use the validate method provided by the Illuminate\Http\Request object.

How do you validate a phone number using a validator?

Mobile Number validation criteria:The first digit should contain number between 7 to 9. The rest 9 digit can contain any number between 0 to 9. The mobile number can have 11 digits also by including 0 at the starting. The mobile number can be of 12 digits also by including 91 at the starting.

How can check email ID is valid or not in laravel?

use the checkdnsrr function. Note: MX records are not required to host a valid working email server. If the MX record does not exist, the @ A record will be used.


1 Answers

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.

like image 70
SlateEntropy Avatar answered Oct 16 '22 21:10

SlateEntropy