我正在使用IValidatableObject来验证以下场景中的复杂对象。
public class Foo {
[Required]
public Bar Foobar { get; set; }
}
public class Bar : IValidatableObject {
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
// check if the current property instance is decorated with the Required attribute
if(TheAboveConditionIsTrue) {
// make sure the Name property is not null or empty
}
}
}
我不知道这是否是最好的方法,如果不是,我很乐意就解决验证的其他方法发表意见。
答案 0 :(得分:0)
为Foo
创建一个实现IValidatableObject
并使其Validate()
方法为虚拟的抽象基类:
public abstract class FooBase : IValidatableObject
{
public string OtherProperty { get; set; }
public Bar Foobar { get; set; }
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
//Validate other properties here or return null
if (String.IsNullOrEmpty(OtherProperty))
results.Add(new ValidationResult("OtherProperty is required", new[] { "OtherProperty" }));
return results;
}
}
现在将您的基类实现为FooRequired
或FooNotRequired
:
public class FooRequired : FooBase
{
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = base.Validate(validationContext).ToList();
result.AddRange(Foobar.Validate(validationContext));
return result;
}
}
public class FooNotRequired : FooBase
{
//No need to override the base validate method.
}
您的Bar
课程仍然如下:
public class Bar : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (String.IsNullOrEmpty(Name))
results.Add(new ValidationResult("Name is required", new[] { "Name" }));
return results;
}
}
用法:
FooBase foo1 = new FooRequired();
foo1.Validate(...);
FooBase foo2 = new FooNotRequired();
foo2.Validate(...);