无论如何,是否可以在 MVC 3 中使用 DataAnnotations 来不允许在文本框中使用 HTML?
我看到了一种允许使用 HTML (AllowHTMLAttribute) 的方法,但是如果我不希望用户在文本框中键入任何 HTML 并且想警告他怎么办?
谢谢 :)
您必须编写一个自定义的 RegularExpressionAttribute ...如下所示:
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);
}
}
您必须注册适配器才能启用客户端验证,因此在 Global.asax 的 Application_Start 中添加以下代码行:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DisallowHTMLAttribute), typeof(RegularExpressionAttributeAdapter));
在您的模型中,将属性添加到您想要禁止 html 标签的属性中,如下所示:
[DisallowHTML]
public string SomeProperty{ get; set; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)