问题
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 :)
回答1:
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; }
回答2:
You may set [ValidateInput(true)]
on controller action
回答3:
Escaping user's text when displaying it may be enough. What if the user wants to post a HTML/XML sample?
<%: Model.UsersContent %>
来源:https://stackoverflow.com/questions/6313662/mvc-3-dataannotations-not-allow-html