如何在laravel 5.2中验证电话号码? [英] How to validate phone number in laravel 5.2?
问题描述
我想验证用户输入的电话号码,其中电话号码应恰好为11,以01开头,值字段应仅为电话号码.如何使用Laravel验证来实现?
I want to validate user input phone number where number should be exactly 11 and started with 01 and value field should be number only. How do I do it using Laravel validation?
这是我的控制人:
public function saveUser(Request $request){
$this->validate($request,[
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'phone' => 'required|min:11|numeric',
'course_id'=>'required'
]);
$user = new User();
$user->name= $request->Input(['name']);
$user->email= $request->Input(['email']);
$user->phone= $request->Input(['phone']);
$user->date = date('Y-m-d');
$user->completed_status = '0';
$user->course_id=$request->Input(['course_id']);
$user->save();
return redirect('success');
}
推荐答案
一种可能的解决方案是使用正则表达式.
One possible solution would to use regex.
'phone' => 'required|regex:/(01)[0-9]{9}/'
这将检查输入以01开头,后跟9个数字.通过使用正则表达式,您不需要numeric
或size
验证规则.
This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numeric
or size
validation rules.
如果您想在其他地方重复使用此验证方法,则最好创建自己的验证规则以验证电话号码.
If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.
在您的AppServiceProvider
的boot
方法中:
Validator::extend('phone_number', function($attribute, $value, $parameters)
{
return substr($value, 0, 2) == '01';
});
这将允许您在应用程序中的任何地方使用phone_number
验证规则,因此您的表单验证可以是:
This will allow you to use the phone_number
validation rule anywhere in your application, so your form validation could be:
'phone' => 'required|numeric|phone_number|size:11'
在验证程序扩展程序中,您还可以检查$value
是否为数字且长度为11个字符.
In your validator extension you could also check if the $value
is numeric and 11 characters long.
这篇关于如何在laravel 5.2中验证电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!