繁体   English   中英

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

[英]How to create a custom Compare attribute with client-side validation?

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

直到最近,我一直在使用MVC已经编写的CompareAttribute来比较两个值,在这种情况下是密码及其确认。 它运行良好,除了此属性不显示由正在比较的属性的[Display(Name = "Name")]属性设置的[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.

这有效,但显然不如它应该的那么好。 New应显示为“ New Password ,由“ Display属性指定。

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

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

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

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))

在我的Global.asax ,但CompareAttributeAdapter实际上并不存在。

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

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

如果您希望自定义比较属性与客户端验证一起使用,则需要实现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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM