Thursday, February 17, 2005

Limiting Characters entered in an html text field Part 2

This is another version of the checkKey() method in the previous posting. It is also usable on IE or Netscape. This function goes about comparing the current key to a string of allowed characters. If it is allowed, it returns true. Otherwise, it returns false. This function is allowing a-z, A-Z, 0-9, -, *, and a space. (Also the Home, End, Delete, and Arrow Keys.)

<script type="text/javascript">
function isValidKey(pEvent)
{
var key;
var keychar;
var lAllowedChars = "abcdefghijklmnopqrstuvwxyz0123456789-*' ";

if (window.event)
key = window.event.keyCode;
else if (pEvent)
key = pEvent.which;
else
return true;

keychar = String.fromCharCode(key).toLowerCase();

// control keys
if ((key==null) (key==0) (key==8)
(key==9) (key==13) (key==27))
return true;

// alphas, numbers, and allow characters
else if (((lAllowedChars).indexOf(keychar) > -1))
return true;
else
return false;
}
</script>

No comments: