【发布时间】:2016-08-24 03:27:41
【问题描述】:
所以我在表单上使用 Fluent Validation。当我单击提交并且没有输入任何内容时,我收到出生日期的验证错误。如果我输入 DoB,那么我会得到 First Name 的验证。
为什么会这样?我不知道我接线错了什么。
我的表格:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(customer => customer.CustomerIncomeInfo.CustomerEmploymentInfoModel.EmployerModel.Id)
<!-- basic customer info -->
<fieldset>
<legend>Customer Info</legend>
@Html.ValidationSummary(false, "Please correct the errors and try again", new { @class = "text-danger" })
<div class="row">
<div class="col-md-6">
<dl class="dl-horizontal">
<dt>@Html.LabelFor(model => model.FirstName)</dt>
<dd>@Html.EditorFor(model => model.FirstName, new {@class = "form-control"})</dd>
</dl>
</div>
<div class="col-md-6">
<dl class="dl-horizontal">
<dt>@Html.LabelFor(model => model.DateOfBirth)</dt>
<dd>@Html.EditorFor(model => model.DateOfBirth, new {@class = "form-control"})</dd>
</dl>
</div>
</div>
</fieldset>
}
我的 Fluent 验证码:
public CustomerValidator()
{
RuleFor(customer => customer.FirstName)
.Length(3, 50)
.NotEmpty()
.WithMessage("Please enter a valid first name");
RuleFor(customer => customer.DateOfBirth).NotEmpty().WithMessage("Please enter a valid date of birth");
}
我的模特:
public class CustomerModel
{
public CustomerModel()
{
}
public Guid Id { get; set; }
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("D.O.B.")]
public DateTime DateOfBirth { get; set; }
}
向 Autofac 注册验证器:
builder.RegisterType<CustomerValidator>()
.Keyed<IValidator>(typeof(IValidator<CustomerModel>))
.As<IValidator>();
【问题讨论】:
-
能否发布执行验证操作的代码以查看如何将错误返回到视图?
-
当您的出生日期为空时,您会收到“请输入有效的出生日期”消息,还是其他消息?我猜你在这种情况下甚至没有通过 FluentValidation 的验证(因为在 mvc 中还有对正确数据类型的验证:并且你尝试将一个空值传递给一个不可为空的 DateTime。如果你写“a”到与 int 类型相关的文本框)
-
Raphaël Althaus,你是对的!使 DoB 可以为空解决了我的问题!如果您可以发布实际回复(最好提供一些验证顺序的详细信息),那么赏金就是您的了 :)
标签: asp.net-mvc fluentvalidation