ASP.NET Numeric Input Validation

There are many ways to validate and force users to type only Numeric data.  You have Bootstrap, MVC, Text Boxes with the attribute of, TextMode="Number", 3rd party controls with Mask Edit such as DevExpress, Infragistics, and others.

The problem with some of these options is that they only work on browsers that support HTML5, some don't play well with IE. In the case of the mask editors I have found these to be very clunky such as you have to hit back space to enter data, delete does not work, or it seems the entry just locks up. 

I own DevExpress but prefer to use the JavaScript method discussed below. It handles the data entry much nicer. 

There is an old standby that I have used from mredkj. It is basically a very well written JavaScript that allows numeric entry only, optional decimal positions allowed as well as prevent negative numbers if you chose to do so.

You can test it out that mredkj blog at this link.

EXAMPLE:

1. Add JS File to your project

 <script src="Scripts/ValidateNumber.js" type="text/javascript" ></script> 

2. Add a TextBox to a page.

<asp:TextBox ID="TxtValScript" runat="server"></asp:TextBox>

3. In the code behind attach to the JavaScript (you can include or exclude decimals / negative values)

TxtValScript.Attributes.Add("onblur", "extractNumber(this,2,false);");
TxtValScript.Attributes.Add("onkeyup", "extractNumber(this,2,false);");
TxtValScript.Attributes.Add("onkeypress", "return blockNonNumbers(this,event,true,false);");
TxtValScript.MaxLength = 8;

The attached ZIP file has the JavaScript. 

Validation.zip (1.64 kb)

Check For Unsaved Changes Before Leaving a Page

After attempting to use JQuery and some other examples I came accross a easy way to handle warning an end user about unsaved changes using JavaScript. This is a modified version to handle, not only leaving the site, but if the end user attempted to navigate to another page on the same site.

In the example below I typed some text and clicked a radio button. Either of these actions would have prompted the warning message to be displayed once leaving the page.

The core of this is a simple JavaScript and checking the contents of a global variable in JavaScript. 

ADDING ATTRIBUTES TO FIELDS

1. On the input fields add onclick (or onchange) attributes to the fields you want to track for any changes.
2. On any links that navigate away from the site or to a new page, add attributes that will check if the JavaScript global varible is TRUE. If it is the post back will stop and the warning message will be shown.  Also, if the user tries to navigate away from the site they will get the warning message as well.
3. Finally on a SAVE button clear the JavaScript global variable.

Sample project attached.

CheckDataEntryChgs.zip (139.98 kb)