Hie*_*ung 3 html asp.net-mvc data-annotations asp.net-mvc-3
无论如何在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);
}
}
Run Code Online (Sandbox Code Playgroud)
您必须注册适配器以启用客户端验证,因此在Global.asax的Application_Start中添加以下代码行:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DisallowHTMLAttribute), typeof(RegularExpressionAttributeAdapter));
Run Code Online (Sandbox Code Playgroud)
在您的模型中,将属性添加到要禁用html标记的属性,如下所示:
[DisallowHTML]
public string SomeProperty{ get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3346 次 |
| 最近记录: |