Reputation: 3455
I have these classes
public class Shape
{
public Shape()
{
ShapeDetails = new List<ShapeDetail>();
}
public int ID { get; set; }
public string Name { get; set; }
public List<ShapeDetail> ShapeDetails { get; set; }
}
public class ShapeValidator : AbstractValidator<Shape>
{
public ShapeValidator()
{
RuleFor(x => x.Name).NotEmpty().Length(1, 225);
}
}
public class ShapeDetail
{
public int ID { get; set; }
public decimal RangeFrom { get; set; }
public decimal RangeTo { get; set; }
public decimal Price { get; set; }
public int ShapeID { get; set; }
[NonPersistent]
public Shape Shape { get; set; }
}
public class ShapeDetailValidator : AbstractValidator<ShapeDetail>
{
public ShapeDetailValidator()
{
RuleFor(x => x.RangeFrom).NotEmpty().LessThan(100);
RuleFor(x => x.RangeTo).NotEmpty().LessThan(100);
RuleFor(x => x.Price).NotEmpty().LessThan(9999999999);
}
}
When I call ModelState.IsValid
on Shape
, it always return true, it seems like it's not validating ShapeDetail
, how do I include the ShapeDetails
in the validation?
Thanks
Upvotes: 1
Views: 223
Reputation: 3455
found the answer, need to add RuleForEach
in ShapeValidator
public class ShapeValidator : AbstractValidator<Shape>
{
public ShapeValidator()
{
RuleFor(x => x.Name).NotEmpty().Length(1, 225);
RuleForEach(x => x.ShapeDetails).SetValidator(new ShapeDetailValidator());
}
}
source: https://fluentvalidation.net/start#collections
Upvotes: 1