gpt4 book ai didi

html - MVC 3 数据注释 : Not allow HTML

转载 作者:搜寻专家 更新时间:2023-10-31 22:50:39 25 4
gpt4 key购买 nike

有没有在 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; }

关于html - MVC 3 数据注释 : Not allow HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6313662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com