我有以下操作:
public void Save (Customer c, IEnumerable <Product> products)
{
// Validate that you have entered at least one product.
if (!produtos.Any())
throw new ArgumentOutOfRangeException("products");
}
内联,不使用继承(例如AbstractValidator),就像使用FluentValidation库的相同操作一样?
答案 0 :(得分:1)
我认为这种验证是不可能的,如果你有一个具有IEnumerable<Product>
类型属性的对象,你可以使用FluentValidation
检查对象是否至少有一个产品。
例如
public class ProductList
{
IEnumerable<Product> Products {get;set;}
var Validator = new ProductListValidator();
public bool IsValid
{
get
{
var res = Validator.Validate(this);
return res.IsValid;
}
}
public IList<ValidationFailure> ValidationResult
{
get
{
var res = Validator.Validate(this);
return res.Errors;
}
}
}
public class ProductListValidator : AbstractValidator<ProductList>
{
public ProductListValidator()
{
RuleFor(i => i.Products).Must(i => i.HasAny()).WithMessage("Your Error Meesage");
}
}
然后
public void Save (Customer c, ProductList products)
{
// Validate that you have entered at least one product.
if (!ProductList.IsValid)
{
ReturnErrorSummary(ProductList.ValidationResult);
}
}
答案 1 :(得分:1)
var validator = new InlineValidator<Person>();
validator.RuleSet("SomeRuleset", ()=>{
validator.RuleFor(x=>x.Name)...etc
});
https://github.com/FluentValidation/FluentValidation/issues/563
答案 2 :(得分:0)
目前尚不支持:
public void DoOperation(List<string> strings)
{
var validator = new InlineValidator<List<string>>();
validator.RuleFor(l => l).Must(l => l.Any()).WithMessage("No one");
validator.ValidateAndThrow(strings)
}
在这种情况下,我们必须手动抛出ValidationException。
像:
public void DoOperation(List<string> strings)
{
if (!strings.Any())
{
var failures = new List<ValidationFailure>();
failures.Add(new ValidationFailure("strings", "Must have at less one."));
throw new ValidationException(failures);
}
}
请参阅: