简体   繁体   English

如何修复旧的javascript以使用jQuery Validate验证国际电话号码?

[英]How can I fix old javascript to validate an international phone number with jQuery Validate?

I found a blog post which shows a method of creating validation for an international phone number. 我找到了一篇博客文章 ,其中显示了一种为国际电话号码创建验证的方法。 The code supplied is: 提供的代码是:

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

I believe it used to work for me but something has changed - possibly a newer version of jQuery - and I'm getting this error: 我相信它曾经为我工作,但发生了一些变化-可能是jQuery的较新版本-而我收到此错误:

Uncaught SyntaxError: Invalid regular expression: /^((+)?[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]+))?$/: Nothing to repeat 

I created a JSBin with the items i'm working with, but I'm not having any luck getting rid of the error. 我使用要处理的项目创建了一个JSBin,但我没有摆脱该错误的任何运气。

How can I fix old javascript to validate an international phone number with jQuery Validate? 如何修复旧的javascript以使用jQuery Validate验证国际电话号码?

ps: I believe I've tried running this with previous versions of jQuery and I'm still getting the error. ps:我相信我已经尝试使用早期版本的jQuery运行它,但仍然出现错误。 I'm not sure what changed. 我不确定发生了什么变化。

Ended up using this: 最终使用了这个:

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

As stated here A comprehensive regex for phone number validation 如此处所述, 用于电话号码验证的综合正则表达式

It will be a lot easier to strip the non-digit characters and create a regex to match only the numbers and extension. 剥离非数字字符并创建一个正则表达式以仅匹配数字和扩展名会容易得多。

Add this to the beginning of your function to remove all non-digits other than x: value.replace("[^\\d+x]", "").match .... 将此添加到函数的开头,以除去x以外的所有非数字: value.replace("[^\\d+x]", "").match ...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM