Dot-Net

如何使用 FluentValidation 將字元串驗證為 DateTime

  • April 26, 2021

使用 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&lt;T&gt; : 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&lt;T, TProperty&gt; IsValidDateTime&lt;T, TProperty&gt;(this IRuleBuilder&lt;T, TProperty&gt; ruleBuilder)
   {
       return ruleBuilder.SetValidator(new DateTimeValidator&lt;TProperty&gt;());
   }
}

然後

public class PersonValidator : AbstractValidator&lt;IPerson&gt;
{
   /// &lt;summary&gt;
   /// Initializes a new instance of the &lt;see cref="PersonValidator"/&gt; class.
   /// &lt;/summary&gt;
   public PersonValidator()
   {
       RuleFor(person =&gt; person.DateOfBirth).IsValidDateTime();   

   }
}

引用自:https://stackoverflow.com/questions/2560829