Monday, December 22, 2008

Validate Decimals with Javascript

Validating a decimal such as a measurement of time or currency (10.5 or 0.4) is as easy as:

function valNum(inNum {
   var RegEx = /[0-9]{1,8}\.?[0-9]{0,2}/;
   var ValidNumber = inNum.match(RegEx);
   return ValidNumber;
}

This function will return the correct number. If you feed in "10.5foo" the function will spit back 10.5. If you feed in "bar" the function will return nothing.

No comments: