How to define a variable length rule (e.g .Length(x,y))?

Aug 5, 2013 at 3:34 AM
Edited Aug 5, 2013 at 3:38 AM

I'm loving the FV framework but have a single rule I can't seem to get right. All the samples I have found have hard coded values in Length!

I have a user defined property where users set the max length of the field and whether the field is required.

I have a rule where max database length is checked, but an optional required check:
            RuleFor(q => q.Answer).NotEmpty().When(a => a.Required);
            RuleFor(q => q.Answer).Length(0, 2000).When(a => !string.IsNullOrWhiteSpace(a.Answer));
But how do I add the additional rule for Length <= q.MaxLength if it's provided and less than 2000?
class Question
  public int MaxLength { get; set; }
  public bool Required { get; set; }
  public string Answer { get; set; }
Aug 5, 2013 at 2:44 PM

Something like this should work:
RuleFor(x => x.Answer).Must((question, answer) => answer.Length <= question.MaxLength)
  .When(question => !string.IsNullOrWhiteSpace(question.Answer) && question.Answer.Length < 2000);