raklos
raklos

Reputation: 28555

fluent validation collection items not null/empty

Im using fluent validation with mvc4

In my Model I have a list:

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

in the view im creating text boxes for each item in the list.

I want to subsequently make sure each field is filled in. (not null/empty)

OrderDetailsViewModelValidator is the validator on the model, what do i need?

Thanks

Upvotes: 17

Views: 32502

Answers (2)

Zack Stone
Zack Stone

Reputation: 712

There is a simpler approach now, using RuleForEach:

RuleForEach(model => model.TransDrops)
    .NotNull()
    .WithMessage("Please fill all items");

Make sure to use NotNull and not NotEmpty, because NotEmpty validates type's default value (in this case: int, it's 0).

You can check for more details in the documentation

Upvotes: 14

Electrionics
Electrionics

Reputation: 6782

First you have to use nullable integer type for collection item, otherwise empty textboxes would be bound to zero value, what makes impossible to distinguish empty textboxes and filled with zeros.

public List<int?> TransDrops { get; set; } 

Next, use predicate validator (Must rule):

RuleFor(model => model.TransDrops)
    .Must(collection => collection == null || collection.All(item => item.HasValue))
    .WithMessage("Please fill all items");

If you need to prevent empty collection being successfully validated, just add NotEmpty() rule before predicate validator: it checks that any IEnumerable not null, and have at least 1 item.

Upvotes: 27

Related Questions