MVC 3 DataAnnotations: Not allow HTML

不打扰是莪最后的温柔 提交于 2020-01-13 18:29:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!