Number Validation Using JavaScript
Usig javascript, the simplest way to check whether the details entered in a text field are numeric is to to loop through the string and compare each character to a pre-defined list of acceptable characters.
<script type=”text/javascript”>
function IsNumber(userText)
{
var ValidChars = “0123456789.”;
var IsNum =true;
var Char;
for (i = 0; i < userText.length && IsNum == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNum = false;
}
}
return IsNum;}
</script>
In this function, we have allowed decimal points and numbers zero through 9.
We use two methods to help us here : the charAt and indexOf.
Using the charAt method, we can find out which character is filling a designated position within a string. We then use the indexOf method to search our ValidChars list of valid characters. If it doesn’t exist, (if ValidChars.indexOf(Char) == -1) this means the user has entered an invalid character. Here’s the full function.
we can also achive the above functionality by using the regular expressions.
<script type=”text/javascript”>
var userText = ‘abcde’;
var reIntegers = /^[0-9.]*$/;
if(userText.match(reIntegers)==null)
{
alert(‘Not a number’);
}else{
alert(‘This is a number’);
}
</script>
in this case also, we have allowed decimal points and numbers zero through 9. using the ‘match’ function we can search the string for the regular expression pattern provided. if any mismatch occured in the patters the “match” function will return a null value.
Filed under: JavaScript