php 如何在laravel 5.2中验证电话号码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36777840/
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-08-26 00:55:53  来源:igfitidea点击:

How to validate phone number in laravel 5.2?

phplaravellaravel-5.2

提问by User57

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?

我想验证用户输入的电话号码,其中数字应该正好是 11 并以 01 开头,值字段应该只是数字。我如何使用 Laravel 验证来做到这一点?

Here is my controller:

这是我的控制器:

  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');

    }

回答by SlateEntropy

One possible solution would to use regex.

一种可能的解决方案是使用正则表达式。

'phone' => 'required|regex:/(01)[0-9]{9}/'

This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numericor sizevalidation rules.

这将检查输入以 01 开头,后跟 9 个数字。通过使用正则表达式,您不需要numericorsize验证规则。

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.

如果您想在其他地方重用此验证方法,最好创建自己的验证规则来验证电话号码。

Docs: Custom Validation

文档:自定义验证

In your AppServiceProvider's bootmethod:

在你AppServiceProviderboot方法中:

Validator::extend('phone_number', function($attribute, $value, $parameters)
{
    return substr($value, 0, 2) == '01';
});

This will allow you to use the phone_numbervalidation 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 $valueis numeric and 11 characters long.

在您的验证器扩展中,您还可以检查 是否$value为数字和 11 个字符长。

回答by vivoconunxino

From Laravel 5.5 on you can use an artisan command to create a new Rule which you can code regarding your requirements to decide whether it passes or fail.

从 Laravel 5.5 开始,您可以使用 artisan 命令来创建一个新规则,您可以根据您的要求对其进行编码,以决定它是通过还是失败。

Ej: php artisan make:rule PhoneNumber

Ej: php artisan make:rule PhoneNumber

Then edit app/Rules/PhoneNumber.php, on method passes

然后编辑app/Rules/PhoneNumber.php,方法通过

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{

    return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\/]?){0,})(?:[\-\.\ \\/]?(?:#|ext\.?|extension|x)[\-\.\ \\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
}

Then, use this Rule as you usually would do with the validation:

然后,像通常使用验证一样使用此规则:

use App\Rules\PhoneNumber;

$request->validate([
    'name' => ['required', new PhoneNumber],
]);

docs

文档

回答by Nady Shalaby

Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
        return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\/]?){0,})(?:[\-\.\ \\/]?(?:#|ext\.?|extension|x)[\-\.\ \\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
    });

Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
        return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
    });

Usage

用法

Insert this code in the app/Providers/AppServiceProvider.phpto be booted up with your application.

This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phonevalidation rule anywhere in your application, so your form validation could be:

将此代码插入要与您的应用程序一起启动的 。 此规则根据上面给定的模式验证电话号码,我在 长时间搜索后发现它与许多国家/地区中最常见的手机或电话号码匹配 这将允许您在应用程序的任何地方使用验证规则,因此您的表单验证可以是: app/Providers/AppServiceProvider.php



phone

 'phone' => 'required|numeric|phone' 

回答by Abhishek

Use required|numeric|size:11Instead of required|min:11|numeric

使用 required|numeric|size:11代替 required|min:11|numeric

回答by aphoe

You can try out this phone validator package. Laravel Phone

你可以试试这个电话验证器包。Laravel 电话

Update

更新

I recently discovered another package Lavarel Phone Validator (stuyam/laravel-phone-validator), that uses the free Twilio phone lookup service

我最近发现了另一个包Lavarel Phone Validator (stuyam/laravel-phone-validator),它使用免费的 Twilio 电话查找服务

回答by Rishi

You can simple use :

您可以简单使用:

        'mobile_number' => ['required', 'digits:10'],

回答by Anh Hoàng

I used the code below, and it works

我使用了下面的代码,它有效

'PHONE' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',

回答by ShaneMit

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

如果您真的考虑过,在验证电话号码时有很多事情需要考虑。(尤其是国际)所以使用包比目前接受的答案要好,如果你想要像正则表达式这样简单的东西,我建议使用比@SlateEntropy 建议的更好的东西。(类似于电话号码验证的综合正则表达式

回答by developer avijit

$request->validate([
    'phone' => 'numeric|required',
    'body' => 'required',
]);