Validating HTML Tags in Textbox/Input Using Javascript
Hi You might have came across this Error when someone entered a html tag in the textbox.. This will generate an error as below:
A potentially dangerous Request.Form value was detected from the client
To Resolve this issue you can use validation using javascript which will validate the input strings and forbade the user from entering HTML tags..
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Restrict HTML Tags</title> <script type="text/javascript"> function Validate(x,y) { str = (document.getElementById('TextBox1')).value; if (str.match(/([\<])([^\>]{1,})*([\>])/i) == null) { y.IsValid = true; } else { y.IsValid = false; } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" /> <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="HTML Tags Not Allowed" ControlToValidate="TextBox1" ClientValidationFunction="Validate"></asp:CustomValidator><br /> <br /> <asp:Button ID="Button1" runat="server" Text="Button" /> <br /> <br /> <asp:Label ID="lblMsg" runat="server"></asp:Label></div> </form> </body> </html>
Another Alternative Approach is to Use Global.asax's Application_Error Event to display a User Friendly Error Message whenever this kind of Error occurs..
protected void Application_Error(object sender, EventArgs e) { Exception appError = Server.GetLastError(); if (appError is HttpRequestValidationException) { Response.Write("<h2>Global Page Error</h2>\n"); Response.Write("<p>" + appError.Message + "</p>\n"); // Clear the error from the server Server.ClearError(); } }
No comments:
Post a Comment
Thank You for Your Comments. We will get back to you soon.