简体   繁体   中英

Fluent Validation on List of string

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM