FluentValidationを使用したDateTimeとして文字列を検証する方法
-
23-09-2019 - |
質問
FluentValidationで、それは?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();
}
}
もしs.DepartureDateTimeはすでにDateTimeプロパティです。それは、日時として、それを検証するためにナンセンスです。 しかし、それならば、文字列は、ダーリンの答えは最高です。
もう一つは、追加します あなたはすべての場所で同じメソッドを繰り返さないためには、外部の静的クラスにBeAValidDate()メソッドを移動する必要があるとします。あなたがそう選択した場合、あなたがするダーリンのルールを変更する必要があります:
RuleFor(s => s.DepartureDateTime)
.Must(d => BeAValidDate(d))
.WithMessage("Invalid date/time");
所属していません StackOverflow