Custom Validate Phone numbers in Laravel 4.2

左心房为你撑大大i 提交于 2019-12-11 10:38:23

问题


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 app/start/global.php this way

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/PhoneValidator.php',

));

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


回答1:


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



来源:https://stackoverflow.com/questions/29259366/custom-validate-phone-numbers-in-laravel-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!