如何使用客户端验证创建自定义Compare属性?

时间:2013-08-27 16:27:28

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

标题说明了一切,但我会在这里添加一些背景知识。

直到最近,我一直在使用MVC已编写的CompareAttribute来比较两个值,在这种情况下是密码及其确认。它运行良好,但此属性不显示显示名称,由要比较的属性的[Display(Name = "Name")]属性设置。

以下是要比较的两个属性:

[Required]
[Display(Name = "New Password")]
public string New { get; set; }

[Compare("New")]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }

验证消息如下:

'Confirm Password' and 'New' do not match.

这很有效,但显然不如它应该的那么好。根据{{​​1}}属性的指定,New应显示为New Password

我已经完成了这项工作,但并非完全如此。以下实现(由于某种原因)修复了未获取属性的指定名称的问题,但我不确定原因:

Display

现在,即使这样可行,客户端验证也不起作用。我在另一个问题中得到了答案,建议使用类似的东西

public class CompareWithDisplayNameAttribute : CompareAttribute
{
    public CompareWithDisplayNameAttribute(string otherProperty)
        : base(otherProperty)
    {
    }
}

在我的DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter)) 中,但Global.asax实际上并不存在。

所以我在这里。我的自定义CompareAttributeAdapter属性正确使用了Display属性,但客户端验证完全丢失。

如何以最干净的方式使用此解决方案进行客户端验证?

1 个答案:

答案 0 :(得分:3)

如果您希望自定义比较属性与客户端验证一起使用,则需要实现IClientValidatable。这有GetValidationRules,您可以在此处进行任何自定义验证。

示例

public class CompareWithDisplayNameAttribute : CompareAttribute, IClientValidatable
{
    public CompareWithDisplayNameAttribute(string otherProperty)
        : base(otherProperty)
    {
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata, ControllerContext context)
    {
        // Custom validation goes here.
        yield return new ModelClientValidationRule();
    }
}