Code to restrict <> characters in textbox using JavaScript

Virendradugar
Posted by Virendradugar under JavaScript category on | Views : 8001
If you donot want user to enter <, > characters in text box, as this creats a security threat then we can disable it usnig JavaScript.

Call this JavaScript function on Page_Load using RegisterStartupScript method.

function RestrictCharacter()
{
var element;
var len=document.forms[0].elements.length;

for(i=0;i<len;i++)
{
element=document.forms[0].elements[i];

if(element.type=='text' || element.type=='textarea')
{
element.attachEvent("onkeypress",function(){if(event.keyCode == 60 || event.keyCode==62 ||
event.keyCode==38 || event.keyCode==39)return false;});
element.attachEvent("onpaste",function()
{
var REGX=new RegExp('<|>|&|\'','gi');
var val=window.clipboardData.getData('Text');
if(REGX.test(val))
return false;
});
element.attachEvent("ondrop",function(){return false;});
}
}
}


This function will not only restrict user to enter these character (<,>), it will also not allow user to paste and drag and drop these character.

Code to call this function in Page_Load

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.RegisterStartupScript(Me, Me.GetType(), "RestrictCharacters", "RestrictCharacter();", True)
End Sub


Hope this helps!!!!!

Comments or Responses

Login to post response