在 Laravel 中验证电话号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52209137/
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
Validate a phone number in Laravel
提问by Jafo
How would I go about validating a number in laravel.
我将如何验证 laravel 中的数字。
I need the number stored in the following format 353861111111.
我需要以以下格式存储的数字 353861111111。
353 will be the prefix, and the user types in the rest. If the user types in 086, this is invalid.
353 将是前缀,用户输入其余部分。如果用户输入086,则无效。
回答by Jayashree
You can use regex as:
您可以将正则表达式用作:
'phone' => 'required|regex:/(353)[0-9]{9}/'
This checks for the pattern with starting with 353
followed by 9
digits having values from 0-9
.
这将检查以 开头353
后跟9
具有值的数字的模式0-9
。
Or you can build a custom validator in boot method of AppServiceProvider.php
:
或者您可以在以下引导方法中构建自定义验证器AppServiceProvider.php
:
Validator::extend('phone_number', function($attribute, $value, $parameters)
{
return substr($value, 0, 3) == '353';
});
This will allow you to use the phone_number validation rule anywhere in your application, so your form validation could be:
这将允许您在应用程序的任何地方使用 phone_number 验证规则,因此您的表单验证可以是:
'phone' => 'required|numeric|phone_number|size:11'
In your validator extension you could also check if the $value
is numeric and 11
characters long.
在您的验证器扩展中,您还可以检查是否$value
为数字和11
字符长。
回答by Jafo
Here is how I did it on an older Laravel 4 project we have to update from time to time:
以下是我在一个旧的 Laravel 4 项目上的做法,我们必须不时更新:
'phone' => 'required|regex:/^\d{3}-\d{3}-\d{4}$/',
回答by Polaris
Try this regex expression:
试试这个正则表达式:
'number' => 'required|regex:^[3][5][3][\d]{8}[\d]$'