Saturday, October 2, 2010

JavaScript isNumeric / Number validation

/* Takes input string and returns true if it is number else returns false */
function IsNumeric(sText){
/* Dont copy paste this code directly as it is containing logical errors */
/* Hint to find the bug in this code : If I pass number to this function it fails. */
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;

for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}
return IsNumber;

}


I used the above code to validate my input string .
Problem comes when we pass null or undefined strings. we need to add a validation for that.

But after adding that validation I thought it's perfect .But still there was one flaw
That is, If I pass a number to this function it fails because sText.length wont work on a number :(

The final code after doing some modifications to the above code is

function IsNumeric(sText){

if(sText == undefined || sText == null ) return false;

sText=''+sText //if input is not a string then we are making it to string.
//Otherwise sText.length wont work.
var ValidChars = "0123456789.";
var Char;


for (i = 0; i < sText.length ; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
return false;
}
}
return true;

}


To realize this I wasted good amount of time..So to save others time I am writing this blog..
Happy Coding and have fun :)

1 comment:

Murthy Kavali said...

OMG ..Above function is failing for '' string..

It's headache to use the above code I am using Ext.isNumber