简体   繁体   English

Javascript电话验证功能在IE8中不起作用

[英]Javascript phone validation function doesn't work in IE8

I have javascript code that validates a phone number for finishing an order. 我有javascript代码,可以验证电话号码以完成订单。

function validatePhoneNumber(phone) {
    var trimPhone = phone.replace(new RegExp(" ","g"),'');  
    var phoneNumber = trimPhone.split(/\d/).length  - 1 ;           
    return phoneNumber >= 10 && phoneNumber <= 16 && phoneNumber === trimPhone.length ;
}

And this is the code for the check-out button 这是结帐按钮的代码

if(!validatePhoneNumber($('#phone').val())){
    $('#phone').css("color", "#ff0000");
    $('#invalidNumberFormat').show();
    submit = false;
}
else{
    $('#invalidNumberFormat').hide();
}

The code works fine in Firefox and Chrome but in IE8 it always returns the error message saying that the string is not between 10 and 16 characters. 该代码在Firefox和Chrome中工作正常,但在IE8中始终返回错误消息,指出字符串不在10到16个字符之间。

What can be the cause? 可能是什么原因?

Your code: trimPhone.split(/\\d/).length - 1 您的代码: trimPhone.split(/\\d/).length - 1

Frankly, that's a really horrible way to find out how many digit characters are in a string! 坦白说,这是找出一个字符串中有多少个数字字符的一种非常糟糕的方法! There are a number of other methods that would be much better than this. 还有许多其他方法会比这更好。

However, more specifically, the problem with it here is that you're hitting a bug in IE8's regex engine. 但是,更具体地说,这里的问题是您遇到了IE8的正则表达式引擎中的错误。

This is a fairly well known bug: When you use .split() , and the result contains consecutive matches with nothing between them, IE8 and earlier will throw away the empty elements from the resulting array. 这是一个众所周知的错误:当您使用.split() ,并且结果包含连续的匹配项且两者之间没有任何匹配时,IE8和更早版本将丢弃结果数组中的空元素。

It's more commonly triggered by trying to parse CSV content with empty values -- eg split(',','x,y,,z') will give you a result with three elements ( x , y and z ) in IE8, whereas other browsers will also give you the empty element between y and z . 通常是通过尝试使用空值来解析CSV内容而触发的-例如split(',','x,y,,z') )在IE8中将为您提供包含三个元素( xyz )的结果,而其他浏览器也会为您提供yz之间的空白元素。

For CSV parsing, it can sometimes be quite a difficult to problem to fix, but your case is much easier, because there's really no need for you to be using this method. 对于CSV解析,有时很难解决问题,但是您的情况要容易得多,因为确实不需要使用此方法。

So the solution in this case here is not to use this method to count the digits. 因此,这种情况下的解决方案是不使用此方法对数字进行计数。

I suggest this as an alternative you could try: 我建议您尝试以下替代方法:

var phoneNumber = trimPhone.replace(/[^\d]/g,'').length;

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

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