Question

How do you validate a list of ints using fluent validation?

My model has:

 public List<int> WindowGlassItems { get; set; }

Model Validator has

RuleFor(x => x.WindowGlassItems).SetCollectionValidator(new WindowGlassItemsValidator());

  public class WindowGlassItemsValidator : AbstractValidator<int>
    {
        public WindowGlassItemsValidator()
        {
            RuleFor(x=>x).NotNull().NotEqual(0).WithMessage("GLASS REQ");
        }
    }

Im getting:

Property name could not be automatically determined for expression x => x. Please specify either a custom property name by calling 'WithName'.

Was it helpful?

Solution

You are seeing that error because you the RuleFor method is expecting a property to be specified. I have been unable to get CollectionValidators to work with primitive types like you have. Instead, I use a custom validation method with Must like this.

The only problem I have with this approach is I am unable to avoid repeating the error message across the 2 validations. If you don't require it when the list is null, you can leave it out after the NotNull call.

    RuleFor(x => x.WindowGlassItems)
        //Stop on first failure to avoid exception in method with null value
        .Cascade(CascadeMode.StopOnFirstFailure)
        .NotNull().WithMessage("GLASS REQ")
        .Must(NotEqualZero).WithMessage("GLASS REQ");

    private bool NotEqualZero(List<int> ints)
    {
        return ints.All(i => i != 0);
    }

OTHER TIPS

I have got the same problem with a List and this was my solution:

RuleFor(rule => rule.MyListOfMyEnum).SetCollectionValidator(new EnumValidator());

public class EnumValidator<T> : AbstractValidator<T>
{
    public EnumValidator(params T[] validValues)
    {
        var s = validValues.Length == 0 ? "---" : string.Join(",", validValues);
        RuleFor(mode => mode).Must(validValues.Contains).WithMessage("'{PropertyValue}' is not a valid value. Valid are [{0}].", s);
    }

    public EnumValidator()
    {
        var s = typeof (T).Name;
        RuleFor(mode => mode).IsInEnum().WithMessage("'{PropertyValue}' is not a valid value for [{0}].", s);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top