且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery插件,用于国际电话号码验证

更新时间:2022-05-26 23:04:57

我建议使用 jQuery验证,然后使用下面的代码扩展了功能,我在此博客文章中找到了.

I would suggest using jQuery Validate and then extended the functionality by using the code below, which I found on this blog post.

它提供了一个不错的代码段(注释中变得更好),可用于国际号码以及美国电话号码.我已经在使用additional methods插件,所以我将方法重命名为intlphone,然后将代码重命名为jQuery之后和document.ready/验证设置之前的网页:

It offers a nice snippet of code (and it gets better in the comments) which you can use for international numbers as well as US phone numbers. I was already using the additional methods plugin so I renamed the method intlphone, and then the code to my web page, after jQuery and before the document.ready / validation setup:

    jQuery.validator.addMethod('intlphone', function(value) { return (value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); }, 'Please enter a valid phone number');

在输入字段中,我想成为一个电话号码,我将该类设置为intlphone,并添加了HTML5属性/属性以提供最小长度(尽管也可以通过在设置验证时指定验证规则来完成此操作) ,所以我的输入是这样的:

On the input field I wanted to be a phone number I set the class to be intlphone and added an HTML5 property / attribute for minimum length (although this could also be done by specifying the validation rules when setting up validation), so my input was something like:

<input class="required intlphone" name="phone" minLength="7" type="text" />

如博客文章所述,它接受数字和-+(),还接受格式为x:ext:

As the blog post says it accepts digits as well as -+() and also spaces and extensions in the format x: or ext:

这不能保证电话号码在100%的时间内都是有效的,但这并不是一个不好的开始.

It's not a guarantee that a phone number will be valid 100% of the time but it's not a bad start.