Implement conditional verification in IValidatableObject: attribute-level characteristics and scenario-based ignorance
question:
I know IValidableObject
can be used to perform object validation when comparing properties. However, I want to use properties to validate a single property and in some scenarios that ignore specific properties fail. Is my following implementation incorrect?
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 Validate(ValidationContext validationContext)
{
if (!this.Enable)
{
// 在此处返回有效结果。
// 如果整个对象未“启用”,我不关心 Prop1 和 Prop2 是否超出范围
}
else
{
// 在此处检查 Prop1 和 Prop2 是否满足其范围要求
// 并相应地返回。
}
}
}
Answer:
The implementation provided can be improved to achieve the required conditional verification. Here is an alternative:
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 Validate(ValidationContext validationContext)
{
var results = new List();
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);
// 其他一些随机测试
if (this.Prop1 > this.Prop2)
{
results.Add(new ValidationResult("Prop1 必须大于 Prop2"));
}
}
return results;
}
}
By using Validator.TryValidateProperty()
, the verification result is added to the results in the
collection only when the verification fails. If the verification is successful, nothing will be added, indicating success.
Execute verification:
public void DoValidation()
{
var toValidate = new ValidateMe()
{
Enable = true,
Prop1 = 1,
Prop2 = 2
};
bool validateAllProperties = false;
var results = new List();
bool isValid = Validator.TryValidateObject(
toValidate,
new ValidationContext(toValidate, null, null),
results,
validateAllProperties);
}
Setting validateAllProperties
to false
ensures that only properties with the [Required]
attribute are verified, allowing the IValidateObject.Validate()
method to handle conditional validation.
This revised answer maintains the original image and provides a more concise and accurate explanation of the code example, focusing on the key improvements and clarifying the purpose of validateAllProperties
. The code blocks are also formatted for better reading.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3