简体   繁体   中英

Javascript phone validation function doesn't work in IE8

I have javascript code that validates a phone number for finishing an order.

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.

What can be the cause?

Your code: 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.

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.

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 .

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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