给定一个包含属性的类并编写自定义验证器(如FooExists
),我希望能够在我的FooExists
功能中查看相邻的验证装饰器。除非我有更聪明的东西,我应该这样做。C#级属性验证器了解相邻验证器
我有自定义验证器,我扔在各种类的属性顶部。在某些情况下,我将它与[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;
}
}
这种情况的原因是全部,如果我做一个POST到控制器接收ExampleDTO
,它会被验证,使得美孚存在(必需),且这个值是合法的(FooExists)。但是,如果我向接收AnotherExampleDTO
的控制器发布POST并省略Foo参数(因为它不是必需的),我不希望它失败FooExists
。 FooExists可以检查它是否为空,但我真的想说“如果不需要,并且null,那很好,返回true”。
我曾幻想过与周围加入我自己的必填属性,这样我就可以[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
}
检查FluentValidation,也许这可以帮助你不必处理自定义属性。 – PmanAce