验证日期时间与FluentValidator [英] Validate DateTime with FluentValidator

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

问题描述

这是我的视图模型类:

 公共类CreatePersonModel
{
    公共字符串名称{;组; }
    公众的DateTime DateBirth {搞定;组; }
    公共字符串电子邮件{获得;组; }
}

CreatePerson.cshtml

  @model ViewModels.CreatePersonModel
@ {
    ViewBag.Title =创建人;
}< H2> @ ViewBag.Title< / H>@using(Html.BeginForm())
{
    <&字段集GT;
        <传奇> RegisterModel< /传说>        @ Html.EditorForModel()        &所述p为H.;
            <输入类型=提交值=创建/>
        &所述; / P>
    < /字段集>
}

CreatePersonValidator.cs

 公共类CreatePersonValidator:AbstractValidator< CreatePersonModel>
{
    公共CreatePersonValidator()
    {
        RuleFor(P => p.Name)
            .NotEmpty()。WithMessage(坎普obrigatório)
            。长度(5,30).WithMessage(德MINIMO {0} e所去的Máximo{1} CARACTERES,5,30)
            。必须((P,N)=> n.Any(C =以及c ==''))WithMessage(德韦康特诺姆ësobrenome)。        RuleFor(P => p.DateBirth)
            .NotEmpty()。WithMessage(坎普obrigatório)
            .LessThan(P => DateTime.Now).WithMessage(数据DEVE ESTAR没有passado);        RuleFor(P => p.Email)
            .NotEmpty()。WithMessage(坎普obrigatório)
            .EmailAddress()。WithMessage(电子邮件inválido)
            .OnAnyFailure(p值=> p.Email =);
    }
}

当试图创建一个人与一个无效的日期格式为:

的意见

正如我CreatePersonModel类中的 DateBirth 属性是的DateTime 键入时,asp.net MVC的验证已经做对我来说。

不过,我想自定义错误消息的使用FluentValidation

我不想改变的财产类型由于各种原因,如:

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

  .LessThan(P => DateTime.Now)

问题

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


解决方案

 公共CreatePersonValidator()
{
    RuleFor(courseOffering => courseOffering.StartDate)
       。必须(BeAValidDate).WithMessage(开始日期);    // ....
}私人布尔BeAValidDate(DateTime的日期)
{
    !返回date.Equals(默认设置(日期时间));
}

This is my ViewModel class:

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

When trying to create a person with an invalid date format:

Observations

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

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:

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

.LessThan (p => DateTime.Now)

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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