實現 IValidatableObject 中的條件驗證:屬性級特性和基於場景的忽略
問題:
我知道 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 Validate(ValidationContext validationContext)
{
if (!this.Enable)
{
// 在此处返回有效结果。
// 如果整个对象未“启用”,我不关心 Prop1 和 Prop2 是否超出范围
}
else
{
// 在此处检查 Prop1 和 Prop2 是否满足其范围要求
// 并相应地返回。
}
}
}
答案:
提供的實現可以改進以實現所需的條件驗證。以下是一種替代方法:
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;
}
}
通過使用 Validator.TryValidateProperty()
,只有當驗證失敗時,驗證結果才會添加到 results
集合中。如果驗證成功,則不會添加任何內容,表示成功。
執行驗證:
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);
}
將 validateAllProperties
設置為 false
可確保僅驗證具有 [Required]
屬性的屬性,從而允許 IValidatableObject.Validate()
方法處理條件驗證。
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 readability.
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3