JavaScript Numeric Validation Function | 2008-01-29

Technology Blog » Web Development

Javascript do not have a build in function to validate the numeric values. Here I wrote a function to encounter that problem......

 

 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.

In this function, we've allowed decimal points and numbers nought 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.

<script type="text/javascript">
/*-----------------------------------------------------------------
The Following Code is written by Andy Ng <[email protected]>
Site: http://www.PCinvent.com
Please do not removed the above credits/copyrights
-----------------------------------------------------------------*/
function IsNumeric(sText)

{
   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;
  
   }
</script>