Discussion:
Stopping user from inputting anything other than letters and numbers
(too old to reply)
Astra
2005-08-11 11:51:59 UTC
Permalink
Hi

I'm using the following routine on a text box to stop users from typing
anything but letters and numbers:

<SCRIPT LANGUAGE="javascript">
<!--
function CheckCodeEntry(e) {

var key = (navigator.appName == "Netscape") ? e.which : e.keyCode;

if (key == 8 || (key > 47 && key < 58) || (key > 64 && key < 91) || (key >
96 && key < 123)) {
return true;
}
else {
return false;
}

// 8 = backspace
// >47 to <58 = 0 to 9
// >64 to <91 = A to Z
// >96 to <123 = a to z

}
//-->
</SCRIPT>

My problem is that if somebody holds down the shift key and say 5 then % is
being entered, which I don't want. This happens for all shift key
functions.

Is there anyway round this?

Thanks

Robbie
g***@teop.org
2005-08-13 16:47:53 UTC
Permalink
Post by Astra
Hi
I'm using the following routine on a text box to stop users from typing
anything but letters and numbers ...
My problem is that if somebody holds down the shift key and say 5 then % is
being entered, which I don't want. This happens for all shift key
functions.
Is there anyway round this?
Yeah. Don't try to identify the keystroke, identify the characters
instead:

<script type="text/javascript">
// Simple regular expression to match non-alphanumeric characters:
reg = new RegExp("[^a-zA-Z0-9]");
function check(field) {
// No point running the function if we don't have any data yet:
if (field.value.length > 0) {
// Run the regular expression against this field's value:
var m = reg.exec(field.value);
// If we found a bad character:
if (m != null) {
// Irritate the user for crimes against our form. Users love to be
abused like this:
alert("Please type only alphanumeric characters or I will irritate
you with this stupid alert.");
// Remove the bad character:
field.value = field.value.substring(0, m.index) +
field.value.substring(m.index+1);
}
}
}
</script>

The function above looks for non-alphanumeric characters in the value
of a supplied formfield object. If it finds one, it removes it. Call it
like this:

<input name="test" type="text" onKeyUp="checkAlphaNum(this)">

You might want to remove the alert line and just put a polite notice
near the form field that it only accepts alphanumeric characters. Note
that any user can disable client-side scripting and defeat this
function if they so desire, so if you really don't want to see
non-alphanumeric characters being sent in this field's data you'll have
to use a server-side script to check the data when the form is
submitted, just to be sure.
--
Kev
Loading...