كيفية التحقق من صحة سلسلة كـ DateTime باستخدام FluentValidation
-
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");