Reputation: 337
My requirement is my text box should not accept the script tags(i.e < and >). When I open the page first time my text box does not allow script tags(i.e < and >).
After some time it allows only alphanumeric characters. When I refresh the page it works fine. Can any one help this. how can i get solution for this? or is there any easy way for this.
my code:
<input name="headerTextBoxs" id="headerTextBox" size="55" type="text" onKeypress="return keyRestricted(event)", onKeydown="return keyRestricted(event)" value="" />
<script type="text/javascript">
function keyRestricted(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var keychar = String.fromCharCode(key);
//alert(keychar);
var keycheck = /[a-zA-Z0-9]/;
if ( (key == 60 || key == 62)) // not allowing script tags
{
if (!keycheck.test(keychar)) {
theEvent.returnValue =false ; //for IE
if (theEvent.preventDefault) theEvent.preventDefault(); //Firefox
}
}
}
</script>
Another way:
My requirement is same that is not allow script tags(i.e < and >). Here the problem is it works fine in mozilla firefox. but in google cromo and IE browsers my textbox not allowing backwards text (i.e left arrow(<-)). simply i wrote like this.
My code:
<input name="headerTextBoxs" id="headerTextBox" size="55" type="text" onkeyup = "this.value=this.value.replace(/[<>]/g,'');" />
Upvotes: 1
Views: 663
Reputation: 5822
I would use the change event to do this.
<input type="text" name="name" onchange="validate(this);"/>
function validate(input_element) {
if( /(<|>)/.test( input_element.value ) ) {
alert( "< and > are not allowed characters" );
}
}
This has less of an impact on performance and you can also use the validate function later on if necessary.
Demo here
Upvotes: 1
Reputation: 535
This works OK for me.
<!DOCTYPE html>
<html>
<head>
<script>
function keyRestricted(e) {
e= e|| window.event;
var key= e.keyCode || e.which;
var keychar= String.fromCharCode(key);
var keycheck = /[a-zA-Z0-9]/;
if ((key == 60 || key == 62)){
if (!keycheck.test(keychar)) {
e.returnValue =false ;
if (e.preventDefault) e.preventDefault();
}
}
}
</script>
</head>
<body>
<input size="55" type="text" onKeypress="keyRestricted(event);" value="" />
</body>
<html>
Upvotes: 1
Reputation: 4114
Try onkeyup
event only if you want to be it more or less responsive.
onchage
event will occur when you will focus out the <input>
, so it will be kinda post factum.
Upvotes: 0