Thursday, September 4, 2008

How to restrict HTML/Javascript tags using Javascript and ASP.NET

There is a security threat that people use scripting tags into the input fields in order to hack/malfunction the application, you may use the steps described below in order to restrict the user not to enter these kind of tags:

Add a text box in your page/control

<asp:TextBox ID="txtComments" runat="server"></asp:TextBox>

Then add an attribute for OnClick and OnKeyPress events

txtComments.Attributes.Add("OnClick", "return RestrictHTMLTags();");

Now you've to define the function RestrictHTMLTags in order to restrict the HTML tags

function RestrictHTMLTags()
for (txt_0=0; txt_0 < txt_box.length; txt_0++)
if (txt_box[txt_0].type=='text')
var str1=parseInt(txt_box[txt_0].value.indexOf('<'))
var str2=parseInt(txt_box[txt_0].value.indexOf('>'))
if (str1 >= 0 || str2 >= 0 )
alert("HTML or JavaScript tags are not allowed")
return false;
return true;

That's how you restrict the user not to enter the restricted tags. Waiting for your comments on this article

No comments: