Laravel 4.2中的自定义验证电话号码 [英] Custom Validate Phone numbers in Laravel 4.2
问题描述
我想使用Laravel 4.2中的定制验证类来验证电话号码.
I want to validate phone numbers using a custom made Validation Class in Laravel 4.2.
这是我的代码:
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);
});
我要接受国际格式的电话号码,后接11位数字(肯尼亚的所有手机均具有12位数字,例如+254721 *** 661).
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).
我已经使用此有用的工具来验证preg_match此正则表达式.
I have use this useful tool to verify the preg_match this regex.
然后我继续以这种方式自动加载app/start/global.php
上的课程
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?
推荐答案
您可以通过以下方式致电电话验证规则
you may call your phone validation rule by
'phone_number' => 'phone',
Validator::make(Input::all(),['phone_number' => 'phone'])
然后移动
//Register your custom validation rule
Validator::resolver(function ($translator, $data, $rules, $messages) {
return new PhoneValidationRule($translator, $data, $rules, $messages);
});
到app\start\global.php
这篇关于Laravel 4.2中的自定义验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!