Monday, July 11, 2011

javascript isNumeric

My google search for a javascript isNumeric function yielded almost no useful information, so I thought I'd post something about validating data quickly using regular expressions.  If you are validating a form, you can use the jquery validation library for this, but I wanted something simpler.

On w3schools, I noticed that javascript supports the regular expression syntax that you'd use in perl or vi. 
var patt=/pattern/modifiers;
In my case, I wanted to see if my string contained anything that wasn't a number, period, or dollar sign.  The following code does the trick
function isNumeric(str) {
   var alpha = /[^0-9$.]/g
   return !alpha.test(str);
}
The regular expression [^0-9$.] searches the string for any character that isn't a number (0-9), a dollar sign, or a period. Alpha.test returns true if any "bad" characters are found.  If alpha.test is false, then we have a valid number




2 comments:

Brian said...

what about commas?

dave said...

Add the comma to the list of "allowed" characters.
[^0-9$.,]