Richie Richie - 1 year ago 144
PHP Question

Custom Validate Phone numbers in Laravel 4.2

I want to validate phone numbers using a custom made Validation Class in Laravel 4.2.

Here is my code:

class PhoneValidationRule extends \Illuminate\Validation\Validator {

public function validatePhone($attribute, $value, $parameters)
return preg_match("/^\+\d[0-9]{11}", $value);


// Register your custom validation rule

Validator::resolver(function($translator, $data, $rules, $messages)
return new PhoneValidationRule($translator, $data, $rules, $messages);

I want to accept phone numbers in international format, followed by 11 digits (All mobile phones in Kenya has 12 digits e.g +254721***661).

I have use this useful tool to verify the preg_match this regex.

I have then gone ahead and autoloaded the Class at
this way




My question is, how will I use the new rule in validating an input?

Answer Source

you may call your phone validation rule by

'phone_number' => 'phone',

Validator::make(Input::all(),['phone_number' => 'phone'])

and move

//Register your custom validation rule
Validator::resolver(function ($translator, $data, $rules, $messages) {
   return new PhoneValidationRule($translator, $data, $rules, $messages);

to app\start\global.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download