A little peek into the dll FluentValidation dll with http://ilspy.net/ and I was able to get inspiration to make the following TrimmedLengthValidator...
public static class DefaultValidatorExtensions
{
public static IRuleBuilderOptions<T, string> TrimmedLength<T>(this IRuleBuilder<T, string> ruleBuilder, int min, int max)
{
return ruleBuilder.SetValidator(new TrimmedLengthValidator(min, max));
}
}
public class TrimmedLengthValidator : PropertyValidator, ILengthValidator, IPropertyValidator
{
public int Min { get; private set; }
public int Max { get; private set; }
public TrimmedLengthValidator(int min, int max)
: this(min, max, () => Messages.length_error)
{ }
public TrimmedLengthValidator(int min, int max, Expression<Func<string>> errorMessageResourceSelector)
: base(errorMessageResourceSelector)
{
this.Max = max;
this.Min = min;
if (max != -1 && max < min)
throw new ArgumentOutOfRangeException("max", "Max should be larger than min.");
}
protected override bool IsValid(PropertyValidatorContext context)
{
if (context.PropertyValue == null)
return true;
int length = context.PropertyValue.ToString().Trim().Length;
if (length < this.Min || (length > this.Max && this.Max != -1))
{
context.MessageFormatter.AppendArgument("MinLength", this.Min).AppendArgument("MaxLength", this.Max).AppendArgument("TotalLength", length);
return false;
}
return true;
}
}
...which means I can simply change my validation to:
RuleFor(x => x.myString).NotEmpty().TrimmedLength(2, 20).WithMessage("Please provide a string with a minium of 2 characters.");
Rock on!