我知道IValidatableObject
是用于验证对象的一种方式,可以让我们将属性相互比较。
我仍然希望有属性来验证单个属性,但我想在某些情况下忽略某些属性的失败。
如果我在下面的情况下没有使用不正确,请问我该如何实现?
public class ValidateMe : IValidatableObject
{
[Required]
public bool Enable { get; set; }
[Range(1, 5)]
public int Prop1 { get; set; }
[Range(1, 5)]
public int Prop2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!this.Enable)
{
/* Return valid result here.
* I don't care if Prop1 and Prop2 are out of range
* if the whole object is not "enabled"
*/
}
else
{
/* Check if Prop1 and Prop2 meet their range requirements here
* and return accordingly.
*/
}
}
}