使用自定义[required]属性时,请使用客户端验证

时间:2012-10-19 06:27:51

标签: asp.net-mvc asp.net-mvc-3 validation client-side

在这个项目中,我们不使用System.ComponentModel.DataAnnotations命名空间中的默认dataannotation属性,但是构建了自定义属性。

因此我们在属性上放置[required]属性,但它是自定义的属性。

对于服务器端验证,我们设法使用自定义验证提供程序覆盖验证,但我们仍然坚持使用客户端验证。

正如我在文档中读到的那样,我看到当你使用默认的[required]属性时,这些属性会在html元素上呈现:

data-val-lengthmax="10" data-val-length-min="3" data-val-required="The ClientName field is required."

我认为这是由框架完成的,框架读取正常的required属性,然后呈现html属性。

我们可以让框架为我们渲染这些属性吗?

2 个答案:

答案 0 :(得分:4)

  

我们可以让框架为我们渲染这些属性吗?

是的,有两种可能性:

  1. 让您的自定义属性实现IClientValidatable接口,您将在其中实现客户端验证规则。
  2. 注册自定义DataAnnotationsModelValidator<TAttribute>,其中TAttribute将是您的自定义验证属性,以及您将在何处实现自定义客户端验证规则(这是Microsoft用于实现Required属性的客户端验证的方法,这就是为什么如果你编写一个自定义验证器属性,从中得到你没有得到客户端验证)。然后,您需要使用DataAnnotationsModelValidatorProvider.RegisterAdapter调用将自定义模型验证程序注册到自定义属性。

答案 1 :(得分:2)

要在自定义属性中启用客户端验证,您可以在属性中实现IClientValidatable界面:

public class requiredAttribute : ValidationAttribute, IClientValidatable
{
    ...

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new[] { new ModelClientValidationRule { ErrorMessage = "<Your error message>", ValidationType = "required" } };
    }
}

作为替代方案,您可以为您的属性实现验证适配器:

public class requiredAttributeAdapter : DataAnnotationsModelValidator<requiredAttribute>
{
    public requiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    { }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new[] { new ModelClientValidationRule { ErrorMessage = "<Your error message>", ValidationType = "required" } };
    }
}

并将其注册到Global.asax中的数据注释验证引擎:

protected void Application_Start()
{
    ...
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(requiredAttribute), typeof(requiredAttributeAdapter));
}

当然,您需要确保在上述类中引用您的属性。