2012-03-16 82 views
2

我有兩個輸入字段的邏輯組,我需要使用JQuery驗證分別進行驗證,但是因爲我使用的是ASP.Net WebForms我只能在頁面上只有一個表單標記。使用ASP.Net WebForms的動態JQuery驗證設置

即使我有一種形式,使用Dave Ward's blog post中的以下技術,我也實現了驗證組。這工作完美。

要驗證事件綁定到ASP.Net形式如下所示:

$("#aspnetForm").validate({ 
    onsubmit: false, 
    ignore: ":hidden", 
    errorClass: 'dynamic-class' 
}); 

我需要通過具有基於我是否想提出一個不同的errorClass值進一步採取這種(和驗證)表格A表格B。例如。 「表格A」將具有「錯誤類別-a」和「表格B」將具有「錯誤類別-B」。我實際上想用其他驗證設置來做到這一點,如errorPlacementerrorElement但我試圖保持這種解釋簡單。

有沒有一種方法可以注入此行爲,而無需破解JQuery驗證插件源代碼?

+0

我發現這個答案是類似的:http://stackoverflow.com/a/4938022/1139752 – 2012-03-17 00:53:49

回答

1

我開始通過添加驗證組(根據Dave Ward's blog post),所以我有兩個邏輯組。在對JQuery Validate文檔和源代碼進行了很長時間的觀察之後,我將調查範圍縮小到一個函數:showErrors()。每次在任何可能顯示錯誤之前都會調用它,無論它是在表單提交事件還是其中一個元素的模糊事件。通過相應地更改設置,可以確保正確的顯示設置始終用於正確的元素。

在下面的代碼中,一個驗證組設置爲在UL列表摘要中顯示錯誤,另一個內聯並使用不同的css類。我已經擴展了showErrors()函數,以根據哪個驗證組包含錯誤的元素來動態地切換錯誤設置。您可以進一步進行此操作,並將設置綁定到驗證容器以避免笨重IF語句,但我已經使用了下面的簡單版本,因爲它更好地說明了解決方案。最後,我打電話給defaultShowErrors(),正如我們期望的那樣,在驗證框架中調用默認函數。

$("#aspForm").validate({ 
     onsubmit: false, 
     // This prevents validation from running on every 
     // form submission by default. 

     // Extend the show errors function 
     showErrors: function (errorMap, errorList) { 

      // here we get the element linked to the error. 
      // we then find out which validation group the element in question 
      // belongs to and set the correct properties 
      if (errorList[0]) { 
       var element = errorList[0].element; 

       // at the time of calling we configure the settings for the validate form 
       if ($(element).parents('.validationGroup').attr("id") == "signup") { 
        this.settings.errorClass = "errorSignUp"; 
        this.settings.errorContainer = $("*[id$='uivalidation']"); 
        this.settings.errorLabelContainer = $("*[id$='uivalidation'] ul"); 
        this.settings.errorElement = "li"; 
       } else { 
        // these are the defaults 
        this.settings.errorClass = "error"; 
        this.settings.errorContainer = $([]); 
        this.settings.errorLabelContainer = $([]); 
        this.settings.errorElement = "label"; 
       } 
      } 

      // call the default show errors function after we have hooked up the correct settings 
      this.defaultShowErrors(); 
     } 
    }); 

這正是我正在尋找的,因爲這意味着我不必對驗證框架進行任何更改。這在下面的完整工作示例中演示,我正在使用CDN for JQuery和JQuery.Validate!

全碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title>Multiple Form Validation</title> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script> 
    <style type="text/css"> 
     * 
     { 
      font-family: Verdana; 
      font-size: 96%; 
     } 
     label 
     { 
      width: 10em; 
      float: left; 
     } 
     label.errorLogin 
     { 
      float: none; 
      color: blue; 
      padding-left: .5em; 
      vertical-align: top; 
     } 
     label.error 
     { 
      float: none; 
      color: red; 
      padding-left: .5em; 
      vertical-align: top; 
     } 
     p 
     { 
      clear: both; 
     } 
     .submit 
     { 
      margin-left: 12em; 
     } 
     em 
     { 
      font-weight: bold; 
      padding-right: 1em; 
      vertical-align: top; 
     } 
    </style> 
    <script type="text/javascript"> 
     $(function() { 

      $("#aspForm").validate({ 
       onsubmit: false, 
       // This prevents validation from running on every 
       // form submission by default. 

       // Extend the show errors function 
       showErrors: function (errorMap, errorList) { 

        // here we get the element linked to the error. 
        // we then find out which validation group the element in question 
        // belongs to and set the correct properties 
        if (errorList[0]) { 
         var element = errorList[0].element; 

         // at the time of calling we configure the settings for the validate form 
         if ($(element).parents('.validationGroup').attr("id") == "signup") { 
          this.settings.errorClass = "errorSignUp"; 
          this.settings.errorContainer = $("*[id$='uivalidation']"); 
          this.settings.errorLabelContainer = $("*[id$='uivalidation'] ul"); 
          this.settings.errorElement = "li"; 
         } else { 
          // these are the defaults 
          this.settings.errorClass = "error"; 
          this.settings.errorContainer = $([]); 
          this.settings.errorLabelContainer = $([]); 
          this.settings.errorElement = "label"; 
         } 
        } 

        // call the default show errors function after we have hooked up the correct settings 
        this.defaultShowErrors(); 
       } 
      }); 

      // Search for controls marked with the causesValidation flag 
      // that are contained anywhere within elements marked as 
      // validationGroups, and wire their click event up. 
      $('.validationGroup .login').click(ValidateAndSubmit); 
      $('.validationGroup .signup').click(ValidateAndSubmit); 

      // Select any input[type=text] elements within a validation group 
      // and attach keydown handlers to all of them. 
      $('.validationGroup :text').keydown(function (evt) { 
       // Only execute validation if the key pressed was enter. 
       if (evt.keyCode == 13) { 
        ValidateAndSubmit(evt); 
       } 
      }); 
     }); 

     function ValidateAndSubmit(evt) { 

      // Ascend from the button that triggered this click event 
      // until we find a container element flagged with 
      // .validationGroup and store a reference to that element. 
      var $group = $(evt.currentTarget).parents('.validationGroup'); 

      var isValid = true; 

      // Descending from that .validationGroup element, find any input 
      // elements within it, iterate over them, and run validation on 
      // each of them. 
      $group.find(':input').each(function (i, item) { 
       if (!$(item).valid()) 
        isValid = false; 
      }); 

      // If any fields failed validation, prevent the button's click 
      // event from triggering form submission. 
      if (!isValid) 
       evt.preventDefault(); 
     } 
    </script> 
</head> 
<body> 
    <form id="aspForm" runat="server"> 
    <fieldset class="validationGroup" id="login"> 
     <div id="uivalidation"> 
      <ul></ul> 
     </div> 
     <legend>Register</legend> 
     <p> 
      <asp:Label ID="uiFirstName" runat="server" AssociatedControlID="uxFirstName" Text="First name:"></asp:Label> 
      <asp:TextBox ID="uxFirstName" runat="server" CssClass="required"></asp:TextBox> 
     </p> 
     <p> 
      <asp:Button ID="uxRegister" runat="server" Text="Register" CssClass="login" /> 
     </p> 
    </fieldset> 
    <fieldset class="validationGroup" id="signup"> 
     <legend>Login</legend> 
     <p> 
      <asp:Label ID="uiUserName" runat="server" AssociatedControlID="uxUserName" Text="User name:"></asp:Label> 
      <asp:TextBox ID="uxUserName" runat="server" CssClass="required"></asp:TextBox> 
     </p> 
     <p> 
      <asp:Button ID="uxLogin" runat="server" Text="Login" CssClass="signup" /> 
     </p> 
    </fieldset> 
    </form> 
</body> 
</html> 

如果這可以進一步改進,請跳,並編輯代碼。