扩展MVC RequiredAttribute

时间:2012-09-24 21:42:59

标签: c# asp.net-mvc asp.net-mvc-2 data-annotations

我有一个不会发送错误消息的ExtendedAttribute扩展类。如果我在调试器中检查它,那么文本就没问题了。

public class VierRequired : RequiredAttribute
{
    public VierRequired(string controlName)
    {
        //...
    }

    public string VierErrorMessage
    {
        get { return ErrorMessage; }
        set { ErrorMessage = value; }
    }

    // validate true if there is any data at all in the object
    public override bool IsValid(object value)
    {
        if (value != null && !string.IsNullOrEmpty(value.ToString()))
            return true;

        return false; // base.IsValid(value);
    }
}

我称之为

[VierRequired("FirstName", VierErrorMessage = "Please enter your first name")]
public string FirstName { get; set; }

和mvc-view

<%: Html.TextBoxFor(model => model.FirstName, new { @class = "formField textBox" })%>
<%: Html.ValidationMessageFor(model => model.FirstName)%>

如果我使用普通的必需注释

,它会起作用
[Required(ErrorMessage = "Please enter your name")]
public string FirstName { get; set; }

但是自定义不会发回任何错误消息

1 个答案:

答案 0 :(得分:27)

当我创建自己的RequiredAttribute衍生物时,我也遇到了客户端验证问题。要修复它,您需要注册您的数据注释,如下所示:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(VierRequired),
            typeof(RequiredAttributeAdapter));

只需在Application_Start()方法中调用此方法,客户端验证就可以正常工作。

如果您在发布表单时属性不起作用,那么这将告诉我您的属性中的逻辑有问题(请检查IsValid方法)。 我也不确定你想要用你的派生数据注释实现什么;你的逻辑似乎正试图做几乎默认属性所做的事情:

取自MSDN文档:

  

如果属性为null,包含空字符串(“”)或仅包含空格字符,则会引发验证异常。

相关问题