2010-01-03 52 views
21

我一直在使用用於.NET的xVal框架進行一些開發,以鏈接服務器端模型的一些驗證規則以及使用jQuery Validation plugin以及jQuery Form plugin提交表單的一些客戶端驗證。如何將jQuery Validation插件與元數據,jQuery Forms和xVal一起使用?

但是,我有問題將它們連接在一起。

我試圖實現以下幾點:

  1. 允許客戶端通過調用rules("add", options")的jQuery插件驗證執行使用定義的規則基本驗證(這是XVAL用來獲取在服務器端定義的規則在模型上)。

  2. 如果客戶端驗證成功,請再次調用服務器以輸入表單數據再次執行驗證(在客戶端驗證的項目上,以及客戶端無法執行的任何其他驗證) 。

  3. 讓服務器返回JSON中的一個對象,指出可能有特定字段的任何錯誤,然後設置字段的錯誤顯示。

我在下面的方式建立在ASP.NET MVC頁面插件的元數據通過對XVAL呼叫:

<%= Html.ClientSideValidation<Model>("model") %> 

這轉化爲在客戶端以下:

<script type="text/javascript"> 
xVal.AttachValidator("model", 
{ 
    "Fields": 
    [ 
     { 
      "FieldName":"title", 
      "FieldRules": 
      [ 
       { 
        "RuleName":"Required", 
        "RuleParameters":{} 
       }, 
       { 
        "RuleName":"StringLength", 
        "RuleParameters": 
        { 
         "MaxLength":"250" 
        } 
       } 
      ] 
     }, 
     { 
      "FieldName":"body", 
      "FieldRules": 
      [ 
       { 
        "RuleName":"Required", 
        "RuleParameters":{} 
       } 
      ] 
     } 
    ] 
}, {}) 
</script> 

上面真的只是轉化到rules("add", options)一系列調用其中的jQuery插件驗證,然後處理。

但是,當試圖通過jQuery表單發佈此表單時,驗證不會發生在表單值上。表單提交,但是這些值根本沒有被驗證。

如何在通過調用ajax調用jQuery驗證插件驗證jQuery Form插件時提交表單?

回答

5

最重要的事情看出來把所有這一切時,合起來就是小片的文檔(這是不是真的明顯的文檔XVAL,其抽象調用rules("add", options)在調用xVal.AttachValidator在)爲rules("add", options)(重點煤礦):

添加指定的規則,並返回 所有規則用於第一匹配 元件。 需要驗證父代 表格,即 $(「form」)。validate()首先被調用 。

,這是特別重要的,當jQuery的表格插件進場時,你希望通過AJAX提交表單,因爲你必須在呼叫submitHandler選項設置爲validate(options),就像這樣:

<script type="text/javascript"> 
    $(document).ready(function() { 
     // Initialize the form. Store the validator. 
     var validator = $("form").validate({ 

      // Called when the form is valid. 
      submitHandler: function(form) { 

       // Submit the form via ajax. 
       $(form).ajaxSubmit({ 

        // The return data type is json. 
        dataType: "json", 

        // The callback on a successful form 
        // submission. 
        success: function(data, statusText) { 

         // If the new location is not null, then 
         // redirect to that location. 
         if (data.data.newLocation) { 
          // Go to the new location. 
          document.location.href = data.data.newLocation; 

          // Get out. 
          return; 
         } 

         // There are errors, pass them to the validator 
         // for display. 
         validator.showErrors(data.data.errors); 
        } 
       }); 
      } 
     }); 
    }); 
</script> 

由於上述關於呼叫報之以rules("add", options)的文件,調用validate(options)必須出現在調用rules("add", options)之前。

如果他們不這樣做,那麼submitHandler將被忽略,永遠不會被調用。

最終,這意味着你的客戶端代碼有看起來像這樣時,把它們放在一起:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script> 
<script type="text/javascript" src="jquery.validate.min.js"></script> 
<script type="text/javascript" src="jquery.form.js"></script> 
<!-- Note this is only needed if using xVal. --> 
<script type="text/javascript" src="xVal.jquery.validate.js"></script> 
<!-- The call to validate the form must come first. --> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     // Initialize the form. 
     $("form").validate({ 

      // Called when the form is valid. 
      submitHandler: function(form) { 

       // Submit the form via ajax. 
       $(form).ajaxSubmit({ 

        // The return data type is json. 
        dataType: "json", 

        // The callback. 
        success: function(data, statusText) { 

         // Alert the users to the message. 
         window.alert(statusText); 
        } 
       }); 
      } 
     }); 
    }); 
</script> 

<!-- Now make the calls to rules("add", options), AFTER the call to --> 
<!-- validate (options). It's separated into another block for  --> 
<!-- emphasis, but could be done in the block above.    --> 
<script type="text/javascript"> 
    // Make calls to rules("add", options). 
</script> 

<!-- Or, if you are using xVal, make the following call in the ASP.NET --> 
<!-- page but again, note it must come AFTER the call to    --> 
<!-- validate(options).            --> 
<%= Html.ClientSideValidation<Model>("model") %> 

最後,所有這一切都連接好,做的最後一件事是什麼在服務器端方法返回時執行。

您會希望從這些調用返回的JSON類似於標準化viewmodel外殼,您可以將響應特定的內容包裝在更標準化的內容中,從而在同類調用中公開所需的信息,像這樣:

{ 
    // An integer, non-zero indicates faulure, with predefined ranges 
    // for standard errors across all operations, with other ranges for custom 
    // errors which are operation-specific. Examples of shared errors 
    // are not authenticated, not authorized, etc, etc. 
    resultCode: 0, 

    // A string, which is to be displayed to the user (usually in the 
    // form of a jQuery dialog, usually used for the common ranges of 
    // errors defined above. 
    message: null, 

    // An object with operation-specific results. 
    data: null 
} 

對於服務器上的錯誤,返回與上面相同,但其具有的用戶應被重定向到成功(或空,如果它沒有成功)的URL位置和地圖如果在字段上有錯誤,可以直接傳遞給showErrors(errors)方法:

{ 
    resultCode: 0, 

    message: null, 

    data: 
    { 
     // Returned as a string. If not null, then this is the url 
     // that the client should be redirected to, as the server-side 
     // operation was successful. 
     newLocation: null, 

     // If not-null, then this is a map which has the names of the 
     // fields with the errors, along with the errors for the fields. 
     errors: 
     { 
      "model.title": "The title already exists in the system.", 
      "model.body": "The body cannot have malicious HTML code in it." 
     } 
    } 
} 

鑑於此,傳遞給ajaxSubmitsuccess field of the options parameter應該清楚:

// The callback on a successful form 
// submission. 
success: function(data, statusText) { 

    // If the new location is not null, then 
    // redirect to that location. 
    if (data.data.newLocation) { 
     // Go to the new location. 
     document.location.href = data.data.newLocation; 

     // Get out. 
     return; 
    } 

    // There are errors, pass them to the validator 
    // for display. 
    validator.showErrors(data.data.errors); 
} 

它所做的就是檢查,看看是否newLocation屬性定義。如果已定義,則將當前文檔重定向到該位置(通常是新保存的資源的URL)。

如果沒有定義,則它需要的地圖,並將其傳遞到showErrors上通過一個調用返回到validate(options)驗證,設定使用由呼叫validate(options)指定的定位和樣式的錯誤消息。

相關問題