Code to restrict <> characters in textbox using JavaScript

Posted by Virendradugar under JavaScript category on | Views : 7935
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;


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;});
var REGX=new RegExp('<|>|&|\'','gi');
var val=window.clipboardData.getData('Text');
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