我了解 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.
*/
}
}
}
最佳答案
首先,感谢 @paper1337 为我指出了正确的资源...我没有注册,所以我不能投票给他,如果有人读到这篇文章,请这样做。
这是完成我想要做的事情的方法。
可验证类:
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)
{
var results = new List<ValidationResult>();
if (this.Enable)
{
Validator.TryValidateProperty(this.Prop1,
new ValidationContext(this, null, null) { MemberName = "Prop1" },
results);
Validator.TryValidateProperty(this.Prop2,
new ValidationContext(this, null, null) { MemberName = "Prop2" },
results);
// some other random test
if (this.Prop1 > this.Prop2)
{
results.Add(new ValidationResult("Prop1 must be larger than Prop2"));
}
}
return results;
}
}
如果验证失败,使用 Validator.TryValidateProperty()
将添加到结果集合中。如果没有失败的验证,则不会向结果集合中添加任何内容,这表明成功。
进行验证:
public void DoValidation()
{
var toValidate = new ValidateMe()
{
Enable = true,
Prop1 = 1,
Prop2 = 2
};
bool validateAllProperties = false;
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(
toValidate,
new ValidationContext(toValidate, null, null),
results,
validateAllProperties);
}
将 validateAllProperties
设置为 false 以使此方法起作用很重要。当 validateAllProperties
为 false 时,仅检查具有 [Required]
属性的属性。这允许 IValidatableObject.Validate()
方法处理条件验证。
关于c# - 如何使用 IValidatableObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3400542/