使用FluentValidator验证DateTime [英] Validate DateTime with FluentValidator

查看:376
本文介绍了使用FluentValidator验证DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 ViewModel 类:

public class CreatePersonModel
{
    public string Name { get; set; }
    public DateTime DateBirth { get; set; }
    public string Email { get; set; }
}

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>
}

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 = "");
    }
}

当尝试创建一个无效的日期格式:

与我的CreatePersonModel类一样, DateBirth 属性是一个 DateTime 类型,asp.net MVC验证已经为我做了。

As in my CreatePersonModel class the DateBirth property is a DateTime type, the asp.net MVC validation has done for me.

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

But I want to customize the error message using the FluentValidation.

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

I do not want to change the type of property for various reasons such as:

CreatePersonValidator.cs 类中,验证是检查日期在过去:

In a CreatePersonValidator.cs class, validation is to check if the date is in the past:

.LessThan (p => DateTime.Now)



问题



如何自定义错误消息而不使用DataAnnotations (使用FluentValidator)。

Question

How to customize the error message without using DataAnnotations (using FluentValidator).

推荐答案

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

    //....
}

private bool BeAValidDate(DateTime date)
{
    return !date.Equals(default(DateTime));
}

这篇关于使用FluentValidator验证DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆