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, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Using Regular Expression to Validate a Decimal Number"
 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions