Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Apply validator to one item in array

$
0
0

Hi Jeremy,

That is a good idea.

I am trying to have similar validation behavior for HttpPostedFileBase or HttpPostedFileBase[].

Consider a form with 3 file inputs linked to a model property of type HttpPostedFileBase[].

If you submit the form without any file you will get context.PropertyValue.Count == 3 and not 0.

Note that all 3 items in context.PropertyValue are null.

So I changed your code to:

  if (files.Count(x => x != null) == 0)
    return false;

Then I tried the following to validate HttpPostedFileBase:

   RuleFor(x => x.File).NotNull().WithMessage("File is required").FileMime("image/jpg").WithMessage("Invalid file");

I get "File is required" when not submitting a file and "Invalid File" when submitting and invalid filIe.

Is makes sense ... Then I tried with HttpPostedFileBase[] and 3 file inputs:

   RuleFor(x => x.Files).NotNull().WithMessage("File is required").FileMime("image/jpg").WithMessage("Invalid file");

The NotNull never fires because context.PropertyValue.Count == 3 but each element is null.

My idea would be an extension that applies NotNull to all elements of a IEnumerable.

Or maybe a new rule that applies another rule to all elements of a IEnumerable.

It could even have some options like:

1 - Rule A should be valid in all items of IEnumerable;

2 - Rule A should be valid in all items of IEnumerable that satisfy condition K. Example:

     RuleFor(x => x.Collection).Each(y => y.NotNull()).When(y => y.ItemValue > K)

Does this make sense?

Thank You,

Miguel


Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>