-
-
Save LSTANCZYK/bc0677a4d4ad69a166a3322bd13ee9b0 to your computer and use it in GitHub Desktop.
NotAllowedHtml.cs is a data annotation addi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.DataAnnotations; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
using System.Web; | |
using System.Xml; | |
using System.Xml.Linq; | |
namespace CommonFunctions.Validation | |
{ | |
public class NotAllowedHtml : ValidationAttribute | |
{ | |
#region properties | |
public bool ShowExceptionDetailsInValidationResult { get; set; } | |
public string ValidationFailureMessage { get; set; } | |
#endregion | |
#region Constructors | |
public NotAllowedHtml() : this("", false) { } | |
public NotAllowedHtml(string message) : this(message, false) { } | |
public NotAllowedHtml(string message, bool returnExceptionDetails) | |
{ | |
ShowExceptionDetailsInValidationResult = returnExceptionDetails; | |
ValidationFailureMessage = message; | |
} | |
#endregion | |
public bool IsInvalidInput(string input) | |
{ | |
var isValidInput = !ContainsOpenAndCloseTags(input); // check 1 | |
if (isValidInput) isValidInput = !ContainsTag(input); // check 2 | |
if (isValidInput) isValidInput = !ContainsTags(input); // check 3 | |
if (!isValidInput) isValidInput = (input != HttpUtility.HtmlEncode(input)); // check 4 | |
return isValidInput; | |
} | |
private static bool ContainsOpenAndCloseTags(string input) | |
{ | |
XElement x = XElement.Parse("<wrapper>" + input + "</wrapper>"); | |
bool isInvalidInput = | |
!(x.DescendantNodes().Count() == 1 && x.DescendantNodes().First().NodeType == XmlNodeType.Text); | |
return isInvalidInput; | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
try | |
{ | |
if (!IsInvalidInput(value.ToString())) | |
return ValidationResult.Success; | |
if (string.IsNullOrEmpty(ValidationFailureMessage)) | |
ValidationFailureMessage = "Error - string contains HTML"; | |
} | |
catch (Exception ex) | |
{ | |
if (ShowExceptionDetailsInValidationResult) | |
return new ValidationResult(ex.ToString()); | |
ValidationFailureMessage = "Error"; | |
} | |
return new ValidationResult(ValidationFailureMessage); | |
} | |
protected static bool ContainsTags (string input) | |
{ | |
const string regexString = @"<\s*([^ >]+)[^>]*>.*?<\s*/\s*\1\s*>"; | |
return Regex.IsMatch(input, regexString); | |
} | |
protected static bool ContainsTag (string input) | |
{ | |
const string regexString = @"<[^>]+>"; | |
return Regex.IsMatch(input, regexString); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment