我知道它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.
*/
}
}
}