C# 如何使用客户端验证创建自定义比较属性?
标题说明了一切,但我会在这里添加一些背景 直到最近,我一直在使用MVC已经编写的C# 如何使用客户端验证创建自定义比较属性?,c#,asp.net-mvc,validation,data-annotations,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(N
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.
这是可行的,但显然没有它应有的那么好。根据显示
属性的指定,新
应读作新密码
我已经让它工作了,虽然还没有完全完成。以下实现(出于某种原因)修复了无法获取属性的指定名称的问题,但我不确定原因:
public class CompareWithDisplayNameAttribute : CompareAttribute
{
public CompareWithDisplayNameAttribute(string otherProperty)
: base(otherProperty)
{
}
}
现在,即使这样做有效,客户端验证也不起作用。我在另一个问题中得到了一个答案,建议使用这样的方法
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))
然而,在我的Global.asax
中,CompareAttributeAdapter
实际上并不存在
我来了。我的自定义CompareWithDisplayName
属性正确使用了Display
属性,但客户端验证完全丢失
如何使客户端验证以尽可能干净的方式使用此解决方案?如果希望自定义比较属性使用客户端验证,则需要实现
IClientValidable
。这里有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();
}
}
公共类CompareWithDisplayNameAttribute:CompareAttribute,IClientValidable
{
公共CompareWithDisplayNameAttribute(字符串otherProperty)
:base(其他属性)
{
}
公共IEnumerable GetClientValidationRules(
ModelMetadata元数据,ControllerContext上下文)
{
//这里是自定义验证。
返回新的ModelClientValidationRule();
}
}