emr*_*azi 5 asp.net-mvc fluentvalidation unobtrusive-validation
在我的ASP.NET MVC 4应用程序中,我试图使用Fluent Validation进行不显眼的客户端验证.
<script src="/Scripts/jquery.validate.min.js" type="text/javascript">
</script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript">
</script>
Run Code Online (Sandbox Code Playgroud)
我在创建新的ASP.NET MVC 4应用程序时提供了VS2010提供的这两个.js文件.我还在我的web.config文件上启用了客户端验证.
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
据我所知,当启用客户端验证和不引人注目的JavaScript时,带有客户端验证规则的输入字段包含data-val ="true"属性,以触发不显眼的客户端验证.我在输入字段中有这些字段.
例如,
<input class="input-validation-error" data-val="true" data-val-
required="error text here" id="purchasePrice"
name="PurchasePrice" type="text" value="">
<span class="field-validation-error error" data-valmsg-for="PurchasePrice"
data-valmsg-replace="true">'Purchase Price' must not be empty.</span>
Run Code Online (Sandbox Code Playgroud)
但是,当我提交表单时,它会发布到控制器,我的模型会在我的控制器代码而不是客户端上进行检查.
编辑:
这是我的表格开头标签.
@using (Html.BeginForm("Create", "Product", FormMethod.Post,
new { enctype = "multipart/form-data", @class = "mainForm",
@id = "productCreateForm" }))
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢.
你添加了MVC的配置吗?
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// this line is required for fluent validation
FluentValidationModelValidatorProvider.Configure();
}
Run Code Online (Sandbox Code Playgroud)
您还需要配置每个视图模型/验证器:
[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
Run Code Online (Sandbox Code Playgroud)
如果这没有帮助,您可以发布一个无法正常工作的验证器示例吗?并非所有验证都可以在客户端完成。例如,以下验证器仅在服务器端工作:
// when validator rules are always server side
public class ServerSideValidator : AbstractValidator<Person> {
public ServerSideValidator() {
When(x => x.Name == "Foo", () => {
RuleFor(x => x.Email).EmailAddress();
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6485 次 |
| 最近记录: |