gpt4 book ai didi

asp.net-mvc - Fluent Validation 不会第一次验证整个表单

转载 作者:行者123 更新时间:2023-12-04 15:54:30 26 4
gpt4 key购买 nike

所以我在表单上使用 Fluent Validation。当我单击提交但没有输入任何内容时,我收到出生日期验证错误。如果我输入 DoB,那么我会得到名字的验证。

为什么会这样?我无法弄清楚我接线错了什么。

我的表格:

 @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");
}
}

希望对你有帮助。

关于asp.net-mvc - Fluent Validation 不会第一次验证整个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113921/

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