Main Super Tables Resources Puzzles
  Search:
Most Popular Other Sites

Number Validation with Javascript Regular Expressions

Rather than rewrite what is already on many websites such as this one, I'm simply going to post some regular expressions that you may find useful for things such as form validation and file parsing.

  • Positive Integer Values: /^(0|[1-9][0-9]*)$/
  • Positive Decimal Values: /(^(0?|[1-9][0-9]*)\.(0*[1-9][0-9]*)$)|(^[1-9]+[0-9]*\.0+$)|(^0\.0+$)/
  • Positive Integer and Decimal Values: /(^(0|[1-9][0-9]*)$)|((^(0?|[1-9][0-9]*)\.(0*[1-9][0-9]*)$)|(^[1-9]+[0-9]*\.0+$)|(^0\.0+$))/
  • Signed Integer and Decimal Values: /(^[+]?0(\.0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)\.(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*\.0+$)/
  • Signed Floating Point Numbers: /^([-+]?[0-9]*\.?[0-9]+)$/   --Source: http://www.regular-expressions.info/floatingpoint.html

You may notice that some of these are really long. This is because they are rather strict when matching valid values. To see why by example, select a tab in the demo below.

Demo

(download the test page)

This script was successfully tested in Windows versions of Internet Explorer 5.5 - 7, Firefox 1.5 - 3, Opera 9 and Safari 3.

Positive Integer Values Positive Decimal Values Positive Integer and Decimal Values Signed Integer and Decimal Values Signed Floating Point Numbers

/^(0|[1-9][0-9]*)$/

 

As I could not test the infinite number of possible values that could be passed into each of these expressions, there is the off chance that some values may test as true when they shouldn't and vice versa. If you happen to come across such a value, please let me know. Thanks!

              

Comments

Paul Posted on March 11, 2008 12:36:04 PM
Matt M Posted on March 11, 2008 12:48:06 PM
grad Posted on May 29, 2008 12:25:39 AM
Santosh Posted on June 05, 2008 06:03:39 AM
rahan Posted on June 29, 2008 05:43:03 AM
Nickname:  ( required )
Email:  ( will not be shown - required )
Website:
Comments: