问题
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