所以我在表单上使用 Fluent Validation。当我单击提交但未输入任何内容时,我收到出生日期验证错误。如果我输入 DoB,则会获得名字验证。
为什么会发生这种情况?我不明白我连接错了什么。
My form:
@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>
}
我的流利验证代码:
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>();
我也在使用Fluent Validation
在我的项目中,它的工作方式与您需要的方式相同。我已经尝试过您的代码与我的代码相同,它工作正常,请参考下面的代码:
/// Test CODE
/// Model Class
[Validator(typeof (CustomerModelValidator))]
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;
}
}
// Validator Class
public class CustomerModelValidator: AbstractValidator < CustomerModel > {
public CustomerModelValidator() {
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");
}
}
希望对您有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)