2009/04/17

How to prevent users from keying in numbers

I saw a pretty neat javascript to prevent (or only allow) users from keying numbers. This works for both IE and Firefox. Here is the scripts:
function onKeyPressBlockNumbers(e)
{
//e.keyCode is for IE; e.which is for Firefox
var key = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(key);
reg = /\d/;
return !reg.test(keychar);
}
This one is the oppsite purpose:
function onKeyPressOnlyNumbers(e)
{
var key = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(key);
reg = /\d/;
return reg.test(keychar);
}
Here is how to use:
<asp:TextBox ID="TextBox1" onkeypress="return onKeyPressBlockNumbers(event);" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" onkeypress="return onKeyPressOnlyNumbers(event);" runat="server"></asp:TextBox>

Note: This cannot prevent users from pasting numbers onto the TextBox.

No comments:

Post a Comment