restrict the user entering nonalphanumeric keys?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to restrict the user entering nonalphanumeric keys using Javascript
onKeypress.
One exception is that I want to allow the user to enter spaces.

How can I do this?

Thanks in Advance.
 
Howdy,

Two variants (both restrict to alphanumeric or nonalphanumeric):


<asp:TextBox runat="server"
onKeyPress="return restrict(this, true);" ID="TextBox1" />
<asp:TextBox runat="server"
onKeyPress="return restrict(this, false);" ID="TextBox2" />

<script type="text/javascript">
function restrict(input, alphanumeric)
{
var regex = alphanumeric ? /[a-zA-Z0-9_ ]/ : /[^a-zA-Z0-9_ ]/;

var code = event.which ? event.which : event.keyCode;

return regex.test(String.fromCharCode(code));
}
</script>

hope this helps
 
Back
Top