Thursday, 17 January 2013

Prevent User from Entering HTML tags in Textbox/TextArea


Prevent User from Entering HTML tags in Textbox/TextArea


In ASP.net this is integrated by default in the page directives:

<%@ Page Language="C#" ValidateRequest="true" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default1" %>



If ValidateRequest is true, the code will trow exeption like:

potentially dangerous Request.Form value was detected from the client (TextBox1="<div>").


Use the following Javascript to prevent the User from Entering HTML Tags in the Textbox/TextArea:


function checkHTMLtags(sender, args)
    {
       var trgtId = document.getElementById("<%=txt1.ClientID%>");
       var str=trgtId.value
       //convert to lowercase
        str=str.toLowerCase()
        //split the string by taking <br> as reference
        var strArray=str.split('<br>');
         if (strArray.length > 0)
          {
            for(k=0;k<strArray.length;k++)
            {
       for(i=0;i<strArray[k].length;i++)
        {
         //check for the presence of < and if available check the following char
         //condition added to include > symbol as well
         if((strArray[k].charAt(i)=='<') || (strArray[k].charAt(i)=='>'))
            {
                        var j=i+1;
                        var str1=strArray[k].charAt(j);
                        var myRegxp=/^[0-9]*$/ ;
                        if(myRegxp.test(str1) == false)
                        {
                           //alert("No HTML Tags allowed in the textarea");
                           trgtId.focus();
                           args.IsValid = false;
                           return;
                        }
                    }
                }
            }
          }
                         
       args.IsValid = true;
       return;
    }
 
Refer This link for more Details:
 
http://msdn.microsoft.com/en-us/library/ff649310.aspx 

1 comment:

  1. Excellent..Thanks. I called this function in dataEvents in colModel. Works fine with me.

    - Ahamed M

    ReplyDelete

Thank You for Your Comments. We will get back to you soon.

back to top