restrict the user entering nonalphanumeric keys?

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.
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top