我有一个模型类:
public class MyModel() { //properties here... }
我想验证MyModel
个对象的列表。所以我创建了这个验证器:
class MyModelListValidator : AbstractValidator<List<MyModel>>
{
public MyModelListValidator ()
{
RuleFor(x => x)
.SetCollectionValidator(new MyModelValidator())
.When(x => x != null);
}
private class MyModelValidator : AbstractValidator<MyModel>
{
public MyModelValidator()
{
//MyModel property validation here...
}
}
}
但上述情况并不奏效。另一种方法是创建一个类:
public class MyModelList()
{
public List<MyModel> Items { get; set; }
}
这样可行。
但是有没有办法在不使用这个额外的类的情况下做到这一点?
答案 0 :(得分:0)
如果您使用数据批注来执行验证,则可能需要自定义属性:
public class EnsureOneElementAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count > 0;
}
return false;
}
}
然后:
[EnsureOneElement(ErrorMessage = "At least a person is required")]
public List<Person> Persons { get; private set; }
or to make it more generic:
public class EnsureMinimumElementsAttribute : ValidationAttribute
{
private readonly int _minElements;
public EnsureMinimumElementsAttribute(int minElements)
{
_minElements = minElements;
}
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count >= _minElements;
}
return false;
}
}
然后:
[EnsureMinimumElements(1, ErrorMessage = "At least a person is required")]
public List<Person> Persons { get; private set; }
Personally I use FluentValidation.NET instead of Data Annotations to perform validation because I prefer the imperative validation logic instead of the declarative. I think it is more powerful. So my validation rule would simply look like this:
RuleFor(x => x.Persons)
.Must(x => x.Count > 0)
.WithMessage("At least a person is required");