How to Code RegEx for Positive Number w/Optional Decimal places and Whitespace

by Updated August 31, 2010

Here's a tip on how to create a Regular Expression to validate a positive number that can optionally have a decimal with decimal places.   The Regular Expression will also be valid if there are any whitespace before or after the number.  I'm using this Regex to evaluate a positive number entered into a TextBox, that's why I'm checking for Whitespace. In my code behind, I am trimming the whitespace from the number entered from the textbox. 

Here is the regular expression that validates a positive number (with optional decimal places and whitespace):

^( *[0-9]*| *)((\.)?[0-9]+ *| *)$

If you use ASP.NET, here is the Validation expression within a RegularExpressionValidator control:

ValidationExpression="^( *[0-9]*| *)((\.)?[0-9]+ *| *)$"


NOTE: This expression will NOT validate true when a  number has a decimal point without decimal places.  For instance,   '3.'  will NOT work, instead you must enter '3.0'.   However, the number '.3' will be valid.




Add your comment

by Anonymous - Already have an account? Login now!
Your Name:  

Enter the text you see in the image below
What do you see?
Can't read the image? View a new one.
Your comment will appear after being approved.

Related Posts

Here's how you can UrlEncode the plus sign (+) in a URL querystring in ASP.NET and then retrieve the plus symbol after UrlDecoding the string. In this example, I will do a postback and redirect the Server.UrlEncoded string to another page. First we will...  more »