9

我有一个不发回错误消息的RequiredAttribute 扩展类。如果我在调试器中检查它,文本就在那里。

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 视图

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

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

4

1 回答 1

30

当我创建自己的RequiredAttribute. 要修复它,您需要像这样注册数据注释:

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

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

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

取自 MSDN 文档:

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

于 2012-09-24T22:01:08.543 回答