jquery plugin for international phone number validations

喜夏-厌秋 提交于 2020-01-31 16:51:06

问题


Can you guys suggest a good telephone number validation plugin for jQuery for both US and International numbers? I Googled a lot but could not find a one that worked well.

It would be great if there was a live validation (i.e.: it validates instantly when the user types the phone number in the input field)


回答1:


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

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

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" />

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

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




回答2:


What is the only thing really(!) valid about a phone number? At least internationally speaking, there is no such thing as a general format for phone numbers. You can write only digits, use some parentheses, dashes, plus signs etc. But what really matters are the digits. There is not even a common length restriction in most countries.

So no, I've not seen a usable phone number validator yet.



来源:https://stackoverflow.com/questions/8397523/jquery-plugin-for-international-phone-number-validations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!