2012-07-26 93 views
5

在我的ASP.NET MVC 4應用程序中,我嘗試使用Fluent驗證進行不顯眼的客戶端驗證。ASP.NET MVC不引人注意的客戶端驗證不起作用

<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時,與客戶端驗證規則輸入字段包含數據-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" })) 

任何想法?謝謝。

+2

愚蠢的問題,但你有沒有確保主JQuery js文件和你在那裏顯示的兩個正確解析? – 2012-07-26 14:42:20

+0

主要的jQuery文件是絕對解決的,我有一個jquery函數正常工作的lof。我不知道他們中的兩個是否已經解決或不誠實。這些文件存在,並且它們似乎可用於Chrome開發人員工具的腳本部分。 – 2012-07-26 14:47:33

+0

另一個愚蠢的問題是,您是否生成了要驗證的模型輸入? – 2012-07-26 14:49:00

回答

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(); 
     }); 
    } 
} 
+0

thx回答,但我擁有所有這些。這是我的驗證碼:RuleFor(product => product.Manufacturer).NotNull(); – 2012-07-26 16:30:22

+0

什麼是製造商?那是一個字符串還是一個類? – Dismissile 2012-07-26 19:12:03

+0

只是一個字符串。 – 2012-07-26 19:20:38