gpt4 book ai didi

asp.net-mvc-3 - 使用FluentValidator验证DateTime

转载 作者:行者123 更新时间:2023-12-03 20:26:05 30 4
gpt4 key购买 nike

这是我的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)来自定义错误消息。

最佳答案

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

//....
}

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

关于asp.net-mvc-3 - 使用FluentValidator验证DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7777985/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com