Reputation: 1173
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
Reputation: 288120
You could just use
var totalNrOfDigits = input.value.match(/\d/g).length;
if(totalNrOfDigits < 10)
alert("Invalid input");
Upvotes: 1
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
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");
}
}
Upvotes: 3
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
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 theisNaN
function is not of typeNumber
, the value is first coerced to aNumber
. The resulting value is then tested to determine whether it isNaN
. 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