我经常在模型中使用CompareAttribute数据注释来验证两个字段是否相等。例如,我们大多数人使用它来比较密码和确认密码字段。
这看似微不足道,但我想知道如何使用这样的注释比较两个字段是不同的。例如,我想验证密码与用户名不同。
对于更复杂的验证,我知道我必须使用自定义验证器,但我只是想知道是否有内置的东西。
谢谢。
答案 0 :(得分:4)
您有两个选择,创建自己的ValidationAttribute继承自CompareAttribute
或继承自ValidationAttribute
。
1)Custom ValidationAttribute继承自CompareAttribute
public class NotEqualAttribute : CompareAttribute
{
public string BasePropertyName { get; private set; }
private const string DefaultErrorMessage = "'{0}' and '{1}' must not be the same.";
public MyCustomCompareAttribut(string otherProperty)
: base(otherProperty)
{
BasePropertyName = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return string.Format(DefaultErrorMessage, name, BasePropertyName);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var result = base.IsValid(value, validationContext);
if (result == null)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
2)Custom ValidationAttribute继承自ValidationAttribute
public class NotEqualAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "'{0}' and '{1}' must not be the same.";
public string BasePropertyName { get; private set; }
public NotEqualAttribute(string basePropertyName)
: base(DefaultErrorMessage)
{
BasePropertyName = basePropertyName;
}
public override string FormatErrorMessage(string name)
{
return string.Format(DefaultErrorMessage, name, BasePropertyName);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(BasePropertyName);
if (property == null)
{
return new ValidationResult(
string.Format(
CultureInfo.CurrentCulture, "{0} is invalid property", BasePropertyName
)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
if (object.Equals(value, otherValue))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
然后您可以使用以下任何一个:
public class YourModelClass
{
public string PropertyA{ get; set; }
[NotEqual("PropertyA")]
public string PropertyB{ get; set; }
}