Malasorte
Malasorte

Reputation: 1173

Bug in a javascript digit counter

My script below checks that a form input contains at least 10 digits, besides other text. Everything works fine, except that it also counts spaces as a digit. Can anyone help with this bug?

Jsfiddle: http://jsfiddle.net/BG4du/

function(){
    var text = input.value;
    var totalNrOfDigits = 0;
    for(var i = 0; i < text.length; i++){
        if(!isNaN(text[i])){
            totalNrOfDigits++;
        }
    }
    if(totalNrOfDigits < 10){
        alert("Invalid input");
    }
}

Upvotes: 3

Views: 162

Answers (5)

Oriol
Oriol

Reputation: 288120

You could just use

var totalNrOfDigits = input.value.match(/\d/g).length;
if(totalNrOfDigits < 10)
    alert("Invalid input");

Demo

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

Do this:

function(){
    var text = input.value.replace(/\s/g,"");
    var totalNrOfDigits = 0;
    for(var i = 0; i < text.length; i++){
        if(!isNaN(text.charAt(i))){
            totalNrOfDigits++;
        }
    }
    if(totalNrOfDigits < 10){
        alert("Invalid input");
    }
}

replace(" ","") just replaces the first occurence. My solution removes all whitespace.

Upvotes: 6

Alex Roth
Alex Roth

Reputation: 162

An alternative to the answers above:

function(){
    var text = input.value;
    var totalNrOfDigits = 0;
    for(var i = 0; i < text.length; i++){
        if(/\d/.test(text[i])){
            totalNrOfDigits++;
        }
    }
    if(totalNrOfDigits < 10){
        alert("Invalid input");
    }
}

Here's an updated JSFiddle

Upvotes: 3

nicael
nicael

Reputation: 18995

Use this:

function() {
    var text = input.value.replace(/\s+/g,""); //removes spaces
    var totalNrOfDigits = 0;
    for(var i = 0; i < text.length; i++){
        if(!isNaN(text[i])){
            totalNrOfDigits++;
        }
    }
    if(totalNrOfDigits < 10){
        alert("Invalid input");
    }
}

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149020

According to MDN, isNaN is broken

Since the very earliest versions of the isNaN function specification, its behavior for non-numeric arguments has been confusing. When the argument to the isNaN function is not of type Number, the value is first coerced to a Number. The resulting value is then tested to determine whether it is NaN. Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." …

I'd recommend something like this instead:

var code = text.charCodeAt(index);
if(code >= 48 && code <= 57){
    totalNrOfDigits++;
}

48 is the character code for '0' and 57 is the character code for '9'.

Upvotes: 6

Related Questions