Validating a Textbox for Decimal Values

by Edward 19 May 2011 18:32

It is always a good idea to try and validate any user input, before the page is submitted or a request is made to the database. This will cut down on unnecessary "back and forth" trips to the database, and also save on performance or showing nasty error pages, if you are not handling exceptions correctly.

To validate any user input, you can use the RegularExpressionValidator control provided with the .Net framework. If you need to validate other forms of input, such as query strings, cookies, or HTML input, you can use the System.Text.RegularExpressions.Regex class.

Here is small code snippet which will accept any numeric/decimal digits (e.g. 100.05), but not any alpha-numeric (e.g. £100.05). You must also have at least one digit before and one after the decimal place. It validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point to be valid.

<asp:TextBox ID="txtAmount" runat="server" />
<asp:Button ID="btnSaveDetails" runat="server" Text="Submit" OnClick="btnSaveDetails_Click" />

<asp:RegularExpressionValidator ID="rvDecimal" ControlToValidate="txtAmount" runat="server"
ErrorMessage="Please enter a valid amount." ValidationExpression="^(-)?\d+(\.\d\d)?$">

Tags: , , , ,

ASP.NET | Other | Technology

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List