[英]C# class property validators knowing about neighboring validators
給定一個具有屬性的類,並編寫自定義驗證器(例如FooExists
,我希望能夠在FooExists
功能中查看相鄰的驗證裝飾器。 除非有更聰明的事情,否則我應該做。
我在各種類的屬性之上都添加了自定義驗證器。 在某些情況下,我將其與[Required]
配對。
在它不是必需的情況下,我想能夠檢查我的被覆蓋的范圍內IsValid
,並且不同的方式處理它。
public class ExampleDTO
{
[Required]
[FooExists]
public string Foo { get; set; }
public string Bar { get; set; }
}
public class AnotherExampleDTO
{
[FooExists]
public string Foo { get; set; }
public bool IsMoo { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
sealed public class FooExistsAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// ideally I could check if this property is required via [Required]
// look things up in the database, return true or false
return true;
}
}
所有這些的原因是,如果我ExampleDTO
收到ExampleDTO
的控制器進行POST,則會對其進行驗證,以確保Foo存在(必需),並且該值合法(FooExists)。 但是,如果我對接收AnotherExampleDTO
的控制器進行POST並忽略Foo參數(因為它不是必需的),則我不希望它失敗FooExists
。 FooExists可以檢查它是否為null,但實際上我想說“如果不是必需的,則為null,可以,返回true”。
我[FooExists(Required=true)]
添加了自己的Required屬性,以便可以[FooExists(Required=true)]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
sealed public class FooExistsAttribute : ValidationAttribute
{
public bool Required { get; set; }
public override bool IsValid(object value)
{
if (!Required && value == null)
return true
// look things up in the database, return true or false
return true;
}
}
但這感覺不對,更不用說我丟失了免費的[Required]
錯誤消息。
我還試圖避免(在這種情況下)在我的DTO中繼承IValidatableObject並將其放入模型中:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// I could check all of the class properties in here
}
簡短答案:否
長答案:您可以通過一些自定義代碼和反射來獲得此行為,但是如果您已概述了這些內容,則不需要這樣做。
[Required]
屬性允許您指定空/空字符串是否有效。 它還僅驗證字符串。 要驗證整數,您需要Range
。
請參閱: MSDN 上的 RequiredAttribute,MSDN上的 RangeAttribute
在您的示例中,我所說的[FooExists]
根本沒有用,因為您使用的是整數值。 如果不需要字段,則根本不需要屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.