2011-02-12 49 views
1

我正在創建一個全新的MVC3網站。在web.config中啓用 客戶端驗證在客戶端驗證在MVC3中爲true時呈現的差異

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

方案1:一個失敗(客戶端)後生成HTML輸出驗證:

<span data-valmsg-replace="true" data-valmsg-for="UserName" class="field-validation-error"> 
    <span htmlfor="UserName" generated="true" class="">Please enter an email address</span> 
</span> 

注意嵌套的span標籤,其中最裏面的標籤有a class =「」

場景#2:自定義服務器端驗證。使用相同的web.config配置,我在服務器上添加了一個驗證以檢查自定義業務規則。驗證失敗,我將該錯誤添加到ModelState中。

的HTML生成這個樣子的:這是產生只有一個span標籤

<span data-valmsg-replace="true" data-valmsg-for="UserName" class="field-validation-error">Please enter a valid email address</span> 

注意,不是一個嵌套的標籤。

這種行爲讓我很難處理我的CSS,因爲我不能只是設置.field-validation-error類的樣式,因爲在我生成的HTML上有兩個不同的最終結果。

總結:客戶端驗證只生成1個span標籤,服務器端驗證生成2個span標籤。

問題:這是框架的縮進行爲還是我做錯了什麼?

+0

「IN SUMMARY」部分實際上是反轉的,客戶端驗證會生成2個span標籤。 – pauloya 2012-09-28 16:00:40

回答

2

這是框架的縮進行爲還是我做錯了什麼?

你沒有做錯任何事。這就是jquery.validate.unobtrusive.js腳本的工作原理。所以你可以稱這是一個缺失的功能,差異,PITA,無論如何,但他們是這樣做的。

這是說的jquery validate plugin是可擴展的,因爲我們喜歡,我們可以調整它:

$.validator.setDefaults({ 
    // customize the way errors are shown 
    showErrors: function (errorMap, errorList) { 
     if (errorList.length < 1) { 
      // because we have customized the way errors are shown 
      // we need to clean them up if there aren't any 
      $('.field-validation-error', this.currentForm).hide().attr('class', 'field-validation-valid'); 
      $('.input-validation-error', this.currentForm).removeClass('input-validation-error'); 
      return; 
     } 
     $.each(errorList, function (index, error) { 
      // simply toggle the necessary classes to the corresponding span 
      // to make client validation generate the same markup as server 
      // side validation 
      var element = $(error.element); 
      element.attr('class', 'input-validation-error'); 
      element.next('span').show().text(error.message).attr('class', 'field-validation-error'); 
     }) 
    } 
}); 
+0

感謝Darin,那就是我一直在尋找的! – nandos 2011-02-13 07:17:55

0

如果你始終要爲您驗證消息嵌套跨度後的服務器驗證失敗(爲造型的原因),你可以執行以下操作:

$(document).ready(function(){ 
    $('.field-validation-error').each(function(){ 
     $(this).html($('<span>').text($(this).text())); 
    }); 
});