Remove Html Tags Or Script Tags In C# String And Also In Client Using Javascript
I need to do a user input validation, and I want it validated both in the client side and in the server side. I have ang textbox that the user can write his comment on the product,
Solution 1:
While RegEx is probably your best bet, you can use this and modify to your liking:
publicstaticstringStripHtml(thisstring source)
{
string[] removeElements = newstring[] { "a", "script" };
string _newString = source;
foreach (string removeElement in removeElements)
{
while (_newString.ToLower().Contains("<" + removeElement.ToLower()))
{
_newString = _newString.Substring(0, _newString.ToLower().IndexOf("<" + removeElement.ToLower())) + _newString.Substring(_newString.ToLower().IndexOf("</" + removeElement.ToLower() + ">") + removeElement.Length + 3);
}
}
return _newString;
}
You'll use string clean = txtInput.Text.StripHtml();
Solution 2:
I am not sure about creating an validation for this. But you can programtically remove the tags using this function.
Use this function to remove the Html tage from the textbox value that user has input
publicstaticstring StripHtml(string html, bool allowHarmlessTags)
{
if (html == null || html == string.Empty)
returnstring.Empty;
if (allowHarmlessTags)
return System.Text.RegularExpressions.Regex.Replace(html, "", string.Empty);
return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty);
}
Solution 3:
If you want prevent javascript injection attacks just encode user input Server.HtmlEncode(message)
.
But if you need to clean some tags then Omar Al Zabir wrote good article Convert HTML to XHTML and Clean Unnecessary Tags and Attributes
// Encode the string inputStringBuildersb=newStringBuilder(
HttpUtility.HtmlEncode(htmlInputTxt.Text));
// Selectively allow <b> and <i>
sb.Replace("<b>", "<b>");
sb.Replace("</b>", "");
sb.Replace("<i>", "<i>");
sb.Replace("</i>", "");
Response.Write(sb.ToString());
I also would like to recomand you check AntiSamy.NET project but I didn't try it by myself.
Post a Comment for "Remove Html Tags Or Script Tags In C# String And Also In Client Using Javascript"