Asp.net-Mvc-3

使用 FluentValidator 驗證日期時間

  • October 15, 2011

這是我的ViewModel類:

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

創建人.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 驗證已為我完成。

但我想使用 FluentValidation自定義錯誤消息。

**由於各種原因,我不想更改屬性的類型,**例如:

在一個CreatePersonValidator.cs 類中,驗證是檢查日期是否過去:

.LessThan (p => DateTime.Now)

如何在不使用 DataAnnotations(使用 FluentValidator)的情況下自定義錯誤消息。

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

   //....
}

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

引用自:https://stackoverflow.com/questions/7777985