MVC 3 DataAnnotations:不允许 HTML

问题描述 投票:0回答:4

是否有办法在 MVC 3 中使用 DataAnnotations 来不允许在文本框中使用 HTML? 我看到了一种允许使用 HTML (AllowHTMLAttribute) 的方法,但是如果我不希望用户在文本框中键入任何 HTML 并且想警告他怎么办?

谢谢:)

html asp.net-mvc asp.net-mvc-3 data-annotations
4个回答
6
投票

你必须编写一个自定义正则表达式属性......像这样:

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; }

0
投票

您可以在控制器操作上设置

[ValidateInput(true)]


0
投票

在显示用户文本时对其进行转义可能就足够了。如果用户想要发布 HTML/XML 示例怎么办?

<%: Model.UsersContent %>


0
投票

我使用此数据注释和正则表达式来检查 html 标签

public class DisallowHTMLAttribute : RegularExpressionAttribute
{
    public DisallowHTMLAttribute()
        : base(@"[^<>&]*")
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format("The field {0} cannot contain html tags", name);
    }
}

在我的模型中:

    [Required]
    [DisallowHTML]
    public string FirstName { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.