checking if parameter is one of 3 values with fluent validation

cs0815 picture cs0815 · Nov 27, 2015 · Viewed 13.9k times · Source

I have a class containing one string property:

public class Bla
{
    public string Parameter { get; set; }
}

I would like to write a custom AbstractValidator, which checks that Parameter is equal to either one of these strings:

str1, str2, str3

I guess this would be a starting point:

RuleFor(x => x.Parameter).Must(x => x.Equals("str1") || x.Equals("str2") || x.Equals("str3")).WithMessage("Please only use: str1, str2, str3");

but can I chain this and also show an error message, ideally without hard-coding the possibilities, e.g.:

Please only use: str1, str2, str3

Answer

Thomas Ayoub picture Thomas Ayoub · Nov 27, 2015

You may do this with a list containing your conditions

List<string> conditions = new List<string>() { str1, str2, str3 };
RuleFor(x => x.Parameter)
  .Must(x => conditions.Contains(x))
  .WithMessage("Please only use: " + String.Join(",", conditions));