Dot-Net
如何使用 FluentValidation 將字元串驗證為 DateTime
使用 FluentValidation,是否可以在無需指定委託的情況下將 a 驗證
string為可解析的?DateTime``Custom()理想情況下,我想說一些類似 EmailAddress 功能的東西,例如:
RuleFor(s => s.EmailAddress).EmailAddress().WithMessage("Invalid email address");所以是這樣的:
RuleFor(s => s.DepartureDateTime).DateTime().WithMessage("Invalid date/time");
RuleFor(s => s.DepartureDateTime) .Must(BeAValidDate) .WithMessage("Invalid date/time");和:
private bool BeAValidDate(string value) { DateTime date; return DateTime.TryParse(value, out date); }或者您可以編寫自定義擴展方法。
您可以按照與 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(); } }