ASP.NET MVC Unobtrusive客户端验证不起作用

时间:2012-07-26 14:37:09

标签: asp.net-mvc unobtrusive-validation fluentvalidation

在我的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>

在创建新的ASP.NET MVC 4应用程序时,我有VS2010提供的这两个.js文件。我还在我的web.config文件上启用了客户端验证。

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

据我所知,当启用客户端验证和不显眼的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>

但是,当我提交表单时,会将其发布到控制器,我的模型会在我的控制器代码而不是客户端上进行检查。

编辑:

这是我的表单开始标记。

@using (Html.BeginForm("Create", "Product", FormMethod.Post, 
   new { enctype = "multipart/form-data", @class = "mainForm",
         @id = "productCreateForm" }))

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:3)

您是否添加了MVC的配置?

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    // this line is required for fluent validation
    FluentValidationModelValidatorProvider.Configure();
}

您还需要配置每个视图模型/验证器:

[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);
    }
}

如果这没有帮助,您是否可以发布一个无法正常工作的验证器示例?并非所有验证都可以在客户端完成。例如,以下验证器仅适用于服务器端:

// when validator rules are always server side
public class ServerSideValidator : AbstractValidator<Person> {
    public ServerSideValidator() {
        When(x => x.Name == "Foo", () => {
            RuleFor(x => x.Email).EmailAddress();
        });
    }
}