Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 535
raklos Avatar asked Apr 01 '14 13:04

raklos


People also ask

Is fluent validation good?

FluentValidation provides a great alternative to Data Annotations in order to validate models. It gives better control of validation rules and makes validation rules easy to read, easy to test, and enable great separation of concerns.

How does fluent validation work?

Fluent validations use Fluent interface and lambda expressions to build validation rules. Fluent validation is a free-to-use . NET validation library that helps you make your validations clean and easy to both create and maintain. It even works on external models that you don't have access to, with ease.

Is fluent validation open source?

FluentValidation is an open source validation library for . NET. It supports a fluent API, and leverages lambda expressions to build validation rules.


2 Answers

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

like image 121
Zack Stone Avatar answered Oct 06 '22 07:10

Zack Stone


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.

like image 31
Evgeny Levin Avatar answered Oct 06 '22 06:10

Evgeny Levin