我使用FluentValidation来验证模型。我已将其设置如下:
public class UserViewModel {
public String Email { get; set; }
public String PhoneNumber { get; set; }
public String FullName { get; set; }
public String CompanyName { get; set; }
}
public class UserViewModelValidation: AbstractValidator<UserViewModel> {
public UserViewModelValidation() {
RuleFor(x => x.Email).NotNull().WithLocalizedMessage(() => ValidationResources.EmailRequired);
RuleFor(x => x.Email).EmailAddress().WithLocalizedMessage(() => ValidationResources.EmailValid);
RuleFor(x => x.PhoneNumber).NotNull().WithLocalizedMessage(() => ValidationResources.PhoneNumberRequired);
RuleFor(x => x.FullName).NotNull().WithLocalizedMessage(() => ValidationResources.FullNameRequired);
RuleFor(x => x.CompanyName).NotNull().WithLocalizedMessage(() => ValidationResources.CompanyNameRequired);
}
}
FluentValidationModelValidatorProvider.Configure();
[HttpPost]
public ActionResult UpdateUser(UserViewModel vm) {
if (!ModelState.IsValid)
return View(vm);
var service = DiConfig.Resolve<IUserService>();
service.Update(vm);
return RedirectToAction("Index");
}
<form action="@Url.Action("UpdateUser", "User")">
@Html.ValidationSummary(true)
<div class="form-input">
@Html.LabelFor(m => m.Email, FormResources.Email)
@Html.TextBoxFor(m => m.Email)
<div class="error-message">@Html.ValidationMessageFor(m => m.Email)</div>
</div>
<div class="form-input">
@Html.LabelFor(m => m.PhoneNumber, FormResources.PhoneNumber)
@Html.TextBoxFor(m => m.PhoneNumber)
<div class="error-message">@Html.ValidationMessageFor(m => m.PhoneNumber)</div>
</div>
<div class="form-input">
@Html.LabelFor(m => m.FullName, FormResources.FullName)
@Html.TextBoxFor(m => m.FullName)
<div class="error-message">@Html.ValidationMessageFor(m => m.FullName)</div>
</div>
<div class="form-input">
@Html.LabelFor(m => m.CompanyName, FormResources.CompanyName)
@Html.TextBoxFor(m => m.CompanyName)
<div class="error-message">@Html.ValidationMessageFor(m => m.CompanyName)</div>
</div>
<div class="form-input">
<input type="submit" value="@FormResources.UpdateButton">
</div>
</form>
客户端验证工作完美。这里没问题。但是,我已经尝试确保即使在浏览器上禁用JS,验证也会起作用。当我提交表单时,我没想到会在页面重新加载后看到错误消息,而没有客户端验证。
但是,结果是 - 根本没有验证消息,但只有query string params
在提交值的URL中。
如何在禁用JavaScript时进行验证?我需要的是(当验证失败时)在帖子和页面重新加载后显示验证消息。
答案 0 :(得分:1)
您可能会错过告诉MVC为特定类运行验证器的部分。 According to the docs,您可以通过修饰模型类来实现:
[Validator(typeof(UserViewModelValidation))]
public class UserViewModel {
public String Email { get; set; }
public String PhoneNumber { get; set; }
public String FullName { get; set; }
public String CompanyName { get; set; }
}
...或者通过配置ValidatorFactory:
FluentValidationModelValidatorProvider.Configure(provider => {
provider.ValidatorFactory = new MyCustomValidatorFactory();
});