Hi there.
I am writing JavaScript to allow user to input only alphabets in the textbox.
I am using regular expression: /[A-Za-z]/g
which is logically correct.
However, IE9, Crome 14 and Firefox 4 allows some specific characters: $%&(
Why is that.
Just copy and save the code as html. And help me to understand whats wrong.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript: Restrict keyboard character input</title>
<script type="text/javascript">
var alphaOnly = /[A-Za-z]/g; //fname,lname,mname
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code == 27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code != 9 && code != 8 && code != 36 && code != 37 && code != 38 && (code != 39 || (code == 39 && character == "'")) && code != 40)
{
if (character.match(restrictionType))
return true;
else
return false;
}
}
</script>
</head>
<body>
<h1>JavaScript: Restrict keyboard character input</h1>
<p>This JavaScript restricts the character input the user can enter into an input or textarea. This is useful in aiding the user enter the correct information such as a number or username. You should also validate the input on the server-side.</p>
<form action="" method="get">
<p><label for="input1">First Name (alphabets only): </label> <input type="text" id="Text1" onkeypress="return restrictCharacters(this, event, alphaOnly);" />
</form>
</body>
</html>
Please help me to understand whats wrong.