自定义数据注释CompareAttribute
本文关键字:CompareAttribute 注释 数据 自定义 | 更新日期: 2023-09-27 18:01:33
我需要比较两个属性在一个类使用。net data annotations
。两个属性中的一个应该被填充,另一个应该是空的。如何重写CompareAttribute
的行为?如果这是不可能的,有什么替代解决方案?
这个类有一个问题:如果属性A被设置为某个值,而属性B已经有了一个值,那么属性A就会像预期的那样无效。在Blanking属性B之后,属性A应该是有效的,但是直到我尝试修改属性A,我才会再次触发验证。是否有一种方法将两者连接在一起,以触发对其中一个更改的验证?
class CustomAttribute : ValidationAttribute
{
private readonly string _other;
public CustomAttribute(string other)
{
_other = other;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_other);
if (property == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _other)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
if (!String.IsNullOrEmpty(value.ToString()) && !String.IsNullOrEmpty(otherValue.ToString()))
{
return new ValidationResult("Test");
}
return null;
}
}
对于这样的东西,我使用ExpressiveAnnotations。它有一个出色的RequiredIf
属性:
[RequiredIf("B == null", ErrorMessage = "Either A or B should be filled")]
public string A { get; set; }
[RequiredIf("A == null", ErrorMessage = "Either A or B should be filled")]
public string B { get; set; }
您可以使用自己的类扩展CompareAttribute
:
public class CustomCompareAttribute: CompareAttribute {
public CustomCompareAttribute(string otherProperty) : base(otherProperty) {
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (OtherProperty == null && value == null) {
return new ValidationResult("Either A or B should be filled");
}
// more checks here ...
}
}