使用FluentValidator验证DateTime

rid*_*nsb 15 datetime fluentvalidation asp.net-mvc-3

这是我的ViewModel类:

public class CreatePersonModel
{
    public string Name { get; set; }
    public DateTime DateBirth { get; set; }
    public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

CreatePerson.cshtml

@model ViewModels.CreatePersonModel
@{
    ViewBag.Title = "Create Person";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm())
{
    <fieldset>
        <legend>RegisterModel</legend>

        @Html.EditorForModel()

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
Run Code Online (Sandbox Code Playgroud)

CreatePersonValidator.cs

public class CreatePersonValidator : AbstractValidator<CreatePersonModel>
{
    public CreatePersonValidator()
    {
        RuleFor(p => p.Name)
            .NotEmpty().WithMessage("campo obrigatório")
            .Length(5, 30).WithMessage("mínimo de {0} e máximo de {1} caractéres", 5, 30)
            .Must((p, n) => n.Any(c => c == ' ')).WithMessage("deve conter nome e sobrenome");

        RuleFor(p => p.DateBirth)
            .NotEmpty().WithMessage("campo obrigatório")
            .LessThan(p => DateTime.Now).WithMessage("a data deve estar no passado");

        RuleFor(p => p.Email)
            .NotEmpty().WithMessage("campo obrigatório")
            .EmailAddress().WithMessage("email inválido")
            .OnAnyFailure(p => p.Email = "");
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试创建具有无效日期格式的人员时:

尝试保存此人时出错

意见

在我的CreatePersonModel类中,DateBirth属性是一个DateTime类型,asp.net MVC验证已经为我完成了.

但我想使用FluentValidation自定义错误消息.

我不想因各种原因更改属性类型,例如:

CreatePersonValidator.cs 课堂上,验证是检查日期是否在过去:

.LessThan (p => DateTime.Now)
Run Code Online (Sandbox Code Playgroud)

如何在不使用DataAnnotations的情况下自定义错误消息(使用FluentValidator).

Dha*_*esh 15

public CreatePersonValidator()
{
    RuleFor(courseOffering => courseOffering.StartDate)
       .Must(BeAValidDate).WithMessage("Start date is required");

    //....
}

private bool BeAValidDate(DateTime date)
{
    return !date.Equals(default(DateTime));
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*hie 5

查看 GitHub 上的 Fluent Validation 文档:

https://github.com/JeremySkinner/FluentValidation/wiki

在应用小于验证器之前,尝试添加正则表达式验证器以确保用户的输入(字符串)可以正确解析为日期。

编辑

在运行了一些测试用例并查看了 Fluent Validator 的源代码后,我承认上述方法行不通。

您获得的标准错误是在模型绑定阶段添加的,该阶段发生在流畅的验证框架可以访问和检查模型之前。

我认为该框架的作者很聪明,并将他们的验证代码注入到模型绑定阶段。看来他们不是。

所以简短的回答是你想做的事情似乎是不可能的。