Search code examples
htmlasp.net-mvcasp.net-mvc-3data-annotations

MVC 3 DataAnnotations: Not allow HTML


Is there anyway to use DataAnnotations in MVC 3 to not allow HTML is used in a textbox? I see a way to allow using HTML (AllowHTMLAttribute) but what if i dont want the user to type any HTML in the textbox and want to warning him?

Thanks :)


Solution

  • You have to write a custom RegularExpressionAttribute ... something like this:

    public class DisallowHTMLAttribute : RegularExpressionAttribute
    {
        public DisallowHTMLAttribute()
            : base(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>")
        {
        }
    
        public override string FormatErrorMessage(string name)
        {
    
            return String.Format("The field {0} cannot contain html tags", name);
    
        }
    }
    

    You must register the adapter to enable client side validation, so in Application_Start in Global.asax add this line of code:

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DisallowHTMLAttribute), typeof(RegularExpressionAttributeAdapter));
    

    And in your model, add the attribute to the properties you want to disallow html tags, like this:

    [DisallowHTML]
    public string SomeProperty{ get; set; }