0

I have a list of strings and I have to define a rule to validate my ModelState in Web API.

Each string element of this list should have length = 2 only. not greater than 2 or less than 2.

I wrote something like this, but it is not working.

RuleFor(m => m.State.TrueForAll(x => x.Length == 2)).Equals(true);

could someone help me out here.

S7H
  • 1,421
  • 1
  • 22
  • 37
  • 1
    Shouldn't that be more like `RuleFor(m => m.State).Must(s => s.TrueForAll(x => x.Length == 2))`; `RuleFor` is meant to select the property you want to validate, then you do the validation after that. – juharr Jun 01 '17 at 12:05
  • Possible duplicate of [How do you validate against each string in a list using Fluent Validation?](https://stackoverflow.com/questions/10190316/how-do-you-validate-against-each-string-in-a-list-using-fluent-validation) – Giovanni Romio Jun 01 '17 at 12:11
  • @juharr This worked! thanks. – S7H Jun 01 '17 at 12:55

1 Answers1

0

Have you tried like this:

bool isAllValid = yourList.All(x => x.Length == 2);

Where yourList be the input List, after execution the value of isAllValid will be true if all the elements of the list are of length 2. if any of the item in the string is less than 2 or greater than 2 then the value of isAllValid will be false. If you enclose this under a method then its signature would be:

public bool IsAllItemsValid(List<string> yourList)
{
    return yourList.All(x => x.Length == 2);
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88