Using Regular Expression to Validate a Decimal Number

One of my clients had a requirement where a decimal input could not exceed 5,2 characters. In other words, the integral part of the decimal could not exceed more than 5 digits and the fractional part could not exceed more than 2 digits.

Eg: 99999.22 where 99999 is integral part and 22 is fractional

Here’s how to solve this requirement using a Regular expression:

<asp:TextBox ID="txtN" runat="server"></asp:TextBox>
asp:RegularExpressionValidator id="myRegex" runat="server"
ControlToValidate="txtN" ValidationExpression="^[0-9]{1,5}(\.[0-9]{0,2})?$"
ErrorMessage="Decimal out of range" />

The expression ^[0-9]{1,5}(\.[0-9]{0,2})?$ checks if the integral part is between 1 to 5 digits and the fractional part is between 0 to 2 digits. Here are some tests.

Decimal Regex

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: