Reputation: 3
Can you please help me to fix my code? I have a textbox that will accept alphanumeric but I want to include a spacebar and period..
please help me.. thank you
<html>
<head>
<script type='text/javascript'>
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
specialKeys.push(38); //Up
specialKeys.push(40); //Down
specialKeys.push(190); //Period
specialKeys.push(32); //Space
function IsAlphaNumeric(e)
{
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 96 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error1").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</head>
<body>
<div id="error1" style="width:300px;background:#FF9999;border:1px solid #FF1919;height:18px;text-align:center;font-family:Verdana;font-size:10px;line-height:18px;display:none;"> ERROR : Special Characters not allowed </div><br>
<input type='text' name='customerName' style='width:400px;text-transform:uppercase' onkeypress="return IsAlphaNumeric(event);"/>
</body>
</html>
Upvotes: 0
Views: 548
Reputation: 3079
Use RegEx to validate input, like this: http://jsfiddle.net/maximgladkov/exyVL/
function IsAlphaNumeric(e) {
var result = e.keyCode > 0 || /^[0-9a-zA-Z .?\/]$/.test(String.fromCharCode(e.charCode));
document.getElementById("error1").style.display = result ? "none" : "inline";
return result;
};
Upvotes: 0
Reputation: 5749
You can just add (keyCode == 32 || keyCode == 46) to your check for the accepted characters:
<html>
<head>
<script type='text/javascript'>
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
specialKeys.push(38); //Up
specialKeys.push(40); //Down
function IsAlphaNumeric(e)
{
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode == 32 || keyCode == 46) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 96 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error1").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</head>
<body>
<div id="error1" style="width:300px;background:#FF9999;border:1px solid #FF1919;height:18px;text-align:center;font-family:Verdana;font-size:10px;line-height:18px;display:none;"> ERROR : Special Characters not allowed </div><br>
<input type='text' name='customerName' style='width:400px;text-transform:uppercase' onkeypress="return IsAlphaNumeric(event);"/>
</body>
</html>
Upvotes: 1