Monday, June 22, 2009

TextBox control (ASP.NET) to accept only numeric values

Very often for data entry screens in a web-application, we have a requirement for having text-box control to accept only numeric characters.. there is no ready-made control available with available server controls.. but there are couple of simple ways in which we can achieve this kind of behavior..

1. simply use a textbox control, and put a regular expression validator on this box.. with regular expression as \d+.. and you are done..

2. use a simple javascript function to do the same, and grab the keypress event for the box..

function blockNumber(e)
{
var keychar;
var reg;
keychar = String.fromCharCode(e.keyCode);
reg = /\d/;
return reg.test(keychar);
}


this function will block user from entering any character other then numbers.. add this function call as attribute for onkeypress event...

txtMyBox.Attributes.Add("onkeypress", "return blockNumber(event);");


and you are done..

isn't this simple or what!!! :)

1 comment:

  1. The above provided javascript works with IE, and fail in Firefox. Textboxes on which the script is hooked will not be able to accept any input, be it character or numeric value.

    will keep you guys posted on the fix..
    Regards
    Nitin

    ReplyDelete