jquery plugin for international phone number validations

后端 未结 2 1452
没有蜡笔的小新
没有蜡笔的小新 2021-02-10 11:26

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.

相关标签:
2条回答
  • 2021-02-10 12:31

    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.

    0 讨论(0)
  • 2021-02-10 12:31

    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.

    0 讨论(0)
提交回复
热议问题