您可以按照与 EmailAddress 完全相同的方式进行操作。
http://fluentvalidation.codeplex.com/wikipage?title=自定义
public class DateTimeValidator<T> : PropertyValidator
{
public DateTimeValidator() : base("The value provided is not a valid date") { }
protected override bool IsValid(PropertyValidatorContext context)
{
if (context.PropertyValue == null) return true;
if (context.PropertyValue as string == null) return false;
DateTime buffer;
return DateTime.TryParse(context.PropertyValue as string, out buffer);
}
}
public static class StaticDateTimeValidator
{
public static IRuleBuilderOptions<T, TProperty> IsValidDateTime<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder)
{
return ruleBuilder.SetValidator(new DateTimeValidator<TProperty>());
}
}
进而
public class PersonValidator : AbstractValidator<IPerson>
{
/// <summary>
/// Initializes a new instance of the <see cref="PersonValidator"/> class.
/// </summary>
public PersonValidator()
{
RuleFor(person => person.DateOfBirth).IsValidDateTime();
}
}