你可以用完全相同的方式完成EmailAddress。
http://fluentvalidation.codeplex.com/wikipage?title=Custom
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();
}
}
這是真棒,但它不會產生正確的HTML5驗證和頁面提交後纔會生效,有沒有什麼辦法讓庫生成對應的html5? – 2014-06-16 08:26:00