MVC 3 DataAnnotes: Do Not Allow HTML

Is it possible to use DataAnnotations in MVC 3 to not allow the use of HTML in a text field? I see a way to allow the use of HTML (AllowHTMLAttribute), but what if I don't want the user to enter any HTML in the text box and want to warn him?

Thank:)

+3
source share
3 answers

You need to write your own 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 the Application_Start in Global.asax add this line of code:

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

And in your model, add an attribute to the properties that you want to disable html tags, for example:

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

[ValidateInput(true)]

0

Resetting user text when displaying it may be enough. What if the user wants to publish an HTML / XML sample?

  <%: Model.UsersContent%>

0
source

All Articles