これは私の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 の検証が行われました。
しかし、 FluentValidation を使用してエラー メッセージをカスタマイズしたいと考えています。
次のようなさまざまな理由で、プロパティのタイプを変更したくありません。
クラスではCreatePersonValidator.cs
、検証とは日付が過去のものかどうかを確認することです。
.LessThan (p => DateTime.Now)
質問
DataAnnotations を使用せずに (FluentValidator を使用して)エラー メッセージをカスタマイズする方法。