2013-02-28 153 views
7

我想驗證我的形式,這樣是出於兩個空字段,至少一個字段必須填寫和兩個字段,也可以填充;但不能留下任何空白。jQuery驗證,出兩個空白領域,至少有一個字段必須填寫或兩者

我使用jQuery-1.9.1-min.js,這裏是我的html頁面。

<form action="#" class="send_form" id="forgot_pass_form" method="POST"> 
      <fieldset> 
       <div class="send_row"> 
        <label class="padding-top10">Email</label> 
        <input type="text" class="send_email" id="email" name="email" /> 
        <em>You need to type an email address</em> 
       </div> 

       <div class="send_row option">OR</div> 

       <div class="send_row"> 
        <label class="padding-top10">Username</label> 
        <input type="text" class="send_username" id="uname" name="uname" /> 
       </div> 


       <div class="send_row send_submitforgotuser"> 
        <input type="submit" value="Submit" /> 
       </div> 
      </fieldset> 
      </form> 

任何建議如何做到這一點....?

SOFAR我已經試過

jQuery.validator.addMethod("require_from_group", function(value, element, options) { 
    alert("xxx"); 
    var valid = $(options[1], element.form).filter(function() { 
     return $(this).val(); 
    }).length >= options[0]; 

    if(!$(element).data('reval')) { 
     var fields = $(options[1], element.form); 
     fields.data('reval', true).valid(); 
     fields.data('reval', false); 
    } 
    return valid; 
}, jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.")); 

仍然沒有得到friutful輸出。

+0

您是否包含jQuery Validate插件?由於您使用了'validator.addMethod()',因此這需要包含jQuery Validate插件並進行正確配置。 – Sparky 2013-02-28 16:56:11

+0

請不要通過發佈重複問題來濫用所以:[驗證(在空白字段中)jquery-1.9.1.min中兩個字段中的任何一個字段(http://stackoverflow.com/questions/15134832/validatein-terms -blank-field-any-one-out-of-two-fields-in-jquery-1-9-1-min) – Sparky 2013-02-28 17:00:28

回答

17

你試圖使用validator.addMethod這是the jQuery Validate plugin一部分。如果你還沒有,你需要在你的代碼中包含這個插件。

然後使用require_from_group規則這已經是the Validate plugin's additional-methods.js file一部分。 (不要忘了包括additional-methods.js文件了。)

rules: { 
    myfieldname: { 
     require_from_group: [1, ".class"] 
    } 
} 
  • 第一個參數是需要的項目數。
  • 第二個參數是分配給您的分組的所有元素的class。我給你的兩個輸入元素添加了一個send類。

  • 還可以使用the groups option到兩個消息合併爲一個。

的jQuery

$(document).ready(function() { 

    $('#forgot_pass_form').validate({ // initialize the plugin 
     groups: { // consolidate messages into one 
      names: "uname email" 
     }, 
     rules: { 
      uname: { 
       require_from_group: [1, ".send"] 
      }, 
      email: { 
       require_from_group: [1, ".send"] 
      } 
     } 
    }); 

    // for your custom message 
    jQuery.extend(jQuery.validator.messages, { 
     require_from_group: jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.") 
    }); 

}); 

工作演示:http://jsfiddle.net/sgmvY/1/


EDITAs per Github, there is an open issuerequire_from_group方法。在修復之前,開發人員在下面推薦這個解決方案。由於您將手動將修改的方法添加到您的代碼中,因此不需要包含additional-methods.js文件。

新工作演示:http://jsfiddle.net/kE7DR/2/

$(document).ready(function() { 

    jQuery.validator.addMethod("require_from_group", function (value, element, options) { 
     var numberRequired = options[0]; 
     var selector = options[1]; 
     var fields = $(selector, element.form); 
     var filled_fields = fields.filter(function() { 
      // it's more clear to compare with empty string 
      return $(this).val() != ""; 
     }); 
     var empty_fields = fields.not(filled_fields); 
     // we will mark only first empty field as invalid 
     if (filled_fields.length < numberRequired && empty_fields[0] == element) { 
      return false; 
     } 
     return true; 
     // {0} below is the 0th item in the options field 
    }, jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.")); 

    $('#forgot_pass_form').validate({ // initialize the plugin 
     groups: { 
      names: "uname email" 
     }, 
     rules: { 
      uname: { 
       require_from_group: [1, ".send"] 
      }, 
      email: { 
       require_from_group: [1, ".send"] 
      } 
     } 
    }); 



}); 
+0

對於遲到的迴應感到抱歉,....感謝你的回答。最重要的一點是:我可以嗎?把它寫成一個函數,然後在jquery驗證中調用它。就像1> function validateUser()然後2>在$(document).ready(function(){// validateUSer();} – bigZero 2013-03-04 06:05:51

+0

@bigZero中,'validate()'只是插件的初始化方式。如果你想在你的函數中測試你的表單的有效性,只要[使用'valid()'](http://docs.jquery.com/Plugins/Validation/valid)任何時候插件初始化後。 – Sparky 2013-03-04 07:10:10

0

@Sparky我想用你的答案來驗證帳戶名和/或密碼的更新。我輸入原始賬戶名稱和密碼,然後點擊更新按鈕,並且執行對原始賬戶名稱和密碼的驗證(即,沒有消息說要輸入新的賬戶或密碼)。我的代碼是:

$(document).ready(function(){ 
$.validator.addMethod(
     "regex", 
     function(value, element, regexp) 
     { 
      if (regexp.constructor != RegExp) 
       regexp = new RegExp(regexp); 
      else if (regexp.global) 
       regexp.lastIndex = 0; 
      return this.optional(element) || regexp.test(value); 
     }, 
     "Please enter correct Characters." 
); 
jQuery.validator.addMethod("require_from_group", function (value, element, options) { 
    var numberRequired = options[0]; 
    var selector = options[1]; 
    var fields = $(selector, element.form); 
    var filled_fields = fields.filter(function() { 
     // it's more clear to compare with empty string 
     return $(this).val() != ""; 
    }); 
    var empty_fields = fields.not(filled_fields); 
    // we will mark only first empty field as invalid 
    if (filled_fields.length < numberRequired && empty_fields[0] == element) { 
     return false; 
    } 
    return true; 
    // {0} below is the 0th item in the options field 
}, jQuery.format("'Please enter either a new Account name and/or a new password'/Please fill out at least {0} of these fields.")); 
$('[data-toggle="tooltip"]').tooltip(); 
$("#contactForm").validate({ 
    groups: { // consolidate messages into one 
     names: "accountName1 enterPassword1" 
    }, 
    rules: { 
     accountName: { 
      required: true, 
      minlength: 2 
     }, 

     enterPassword: { 
      required: true, 
      minlength: 8 
     }, 

     accountName1: { 
      require_from_group: [1, ".send"], 
      minlength: 2 
     }, 

     accountName2: { 
      minlength: 2, 
      equalTo: "#accountName1" 
     }, 

     enterPassword1: { 
      require_from_group: [1, ".send"], 
      regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[[email protected]$!%*?&])[A-Za-z\[email protected]$!%*?&]{8,}/, 
      minlength: 8 
     }, 

     enterPassword2: { 
      regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[[email protected]$!%*?&])[A-Za-z\[email protected]$!%*?&]{8,}/, 
      minlength: 8, 
      equalTo: "#enterPassword1" 
     } 
    }, 

    messages: { 
     accountName: { 
      required: "Please enter your current account name.", 
      minlength: "Your account name must consist of at least 2 characters." 
     }, 

     enterPassword: { 
      required: "Please enter your current password.", 
      minlength: "Your password must consist of at least 8 characters." 
     }, 

     accountName1: { 
      minlength: "Your account name must consist of at least 2 characters." 
     }, 

     accountName2: { 
      minlength: "Your account name must consist of at least 2 characters.", 
      equalTo: "Your confirmation account name does not match the original." 
     }, 

     enterPassword1: { 
      regex: "Please nter at least 8 characters containing at least 1 lower case, 1 upercase, 1 special and 1 numeric..", 
      minlength: "Your password must consist of at least 8 characters." 
     }, 

     enterPassword2: { 
      regex: "Please enter at least 8 characters containing at least 1 lower case, 1 upercase, 1 special and 1 numeric..", 
      minlength: "Your password must consist of at least 8 characters.", 
      equalTo: "Your confirmation password does not match the original." 
     } 
    }, 

    submitHandler : function(contactForm) { 
     //do something here 
     var frm = $('#contactForm'); 
     //alert($("#accountName1").val()); 

     $.ajax({ 
      type: "POST", 
      url: "UpdateAccountView", 
      cache: false, 
      data: frm.serialize(), 
      success: function(data){ 
       console.log('Submission was successful.'); 
       console.log(data); 

       $("#accountName").focus(); 
       $('#ajaxGetUserServletResponse').text(data); 
      } 
     }); 
    } 
});  
}); // end document.ready 
相關問題