在 Laravel 4.2 中自定义验证电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29259366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:13:04  来源:igfitidea点击:

Custom Validate Phone numbers in Laravel 4.2

phpregexvalidationlaravellaravel-4

提问by Richie

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

我想在 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).

我想接受国际格式的电话号码,后跟 11 位数字(肯尼亚的所有手机都是 12 位数字,例如 +254721***661)。

I have use this useful toolto verify the preg_match this regex.

我已经使用这个有用的工具来验证这个正则表达式的 preg_match。

I have then gone ahead and autoloaded the Class at app/start/global.phpthis way

然后我继续以app/start/global.php这种方式自动加载类

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?

我的问题是,我将如何使用新规则来验证输入?

采纳答案by terry low

you may call your phone validation rule by

您可以通过以下方式调用您的电话验证规则

'phone_number' => 'phone',

Validator::make(Input::all(),['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

app\start\global.php