只有当字段不为空时,是否有办法触发比较数据注释?如果没有,那么另一种方法是什么?
以下代码始终触发比较数据注释,无论它是否具有值。
[EmailAddress]
[Required]
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
[Display(Name = "Confirm Email Address")]
[Compare("EmailAddress", ErrorMessage = "The email addresses do not match.")]
public string ConfirmEmailAddress { get; set; }
答案 0 :(得分:2)
使用您自己的属性扩展属性可能最简单:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class CompareEnhancedAttribute : CompareAttribute
{
public bool AllowEmptyStrings { get; set; }
public CompareEnhancedAttribute(string otherProperty)
: base(otherProperty)
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (AllowEmptyStrings && string.IsNullOrEmpty(value?.ToString()))
{
return ValidationResult.Success;
}
else
{
return base.IsValid(value, validationContext);
}
}
}
然后像这样使用它:
public sealed class ContactModel
{
/* omitted other attributes */
public string EmailAddress { get; set; }
[CompareEnhanced("EmailAddress", AllowEmptyStrings = true)]
public string ConfirmEmailAddress { get; set; }
}