LSTANCZYK
9/25/2017 - 1:54 AM

NotAllowedHtml.cs is a data annotation addi

NotAllowedHtml.cs is a data annotation addi

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);
        }
    }
}