Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Javascript numeric validation (See related posts)

I've seen a lot of takes on numeric validation, and most have serious flaws. For example, (!isNaN) returns inconsistent results and shouldn't be used to verify numericality. This should cover all cases, and supports a decimal point as well as negative numbers.

   1  
   2  function isNumeric(value) {
   3    if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
   4    return true;
   5  }


This logic is straight-forward: if the parameter isn't null, convert it to a string and match it against a RegEx to throw out false cases. Otherwise, return true.

Comments on this post

aamirafridi posts on Jul 23, 2008 at 11:52
It can be done also as:

   1  
   2  function IsNumeric(strString) //  check for valid numeric strings	
   3  {
   4  	if(!/\D/.test(strString)) return true;//IF NUMBER
   5  	else if(/^\d+\.\d+$/.test(strString)) return true;//IF A DECIMAL NUMBER HAVING AN INTEGER ON EITHER SIDE OF THE DOT(.)
   6  	else return false;
   7  }

You need to create an account or log in to post comments to this site.


Click here to browse all 5355 code snippets

Related Posts