2013-02-28 14 views
7

Voglio convalidare il mio modulo in modo che non ci siano due campi vuoti, almeno un campo deve essere compilato e due campi possono anche essere pieno; ma non può lasciare alcun campo vuoto.jQuery Convalida, tra due campi vuoti, almeno un campo deve essere compilato o entrambi

Sto usando jquery-1.9.1-min.js e qui è la mia pagina 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> 

Qualche suggerimento come si fa ....?

sofar ho cercato

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.")); 

Ancora non ottenere uscita friutful.

+0

Avete incluso il plugin jQuery Validate? Dato che stai usando 'validator.addMethod()', questo richiede che il plugin jQuery Validate sia incluso e configurato correttamente. – Sparky

+0

Si prega di non abusare di SO postando domande doppie: [Convalidare (in termini di campo vuoto) qualsiasi campo su uno di due in jquery-1.9.1.min] (http://stackoverflow.com/questions/15134832/validatein-terms -blank-field-any-one-of-two-fields-in-jquery-1-9-1-min) – Sparky

risposta

17

Si sta tentando di utilizzare validator.addMethod che fa parte di the jQuery Validate plugin. Dovrai includere questo plugin nel tuo codice se non lo hai già fatto.

Quindi utilizzare la regola require_from_group che fa già parte di the Validate plugin's additional-methods.js file. (Non dimenticare di includere il file additional-methods.js troppo.)

rules: { 
    myfieldname: { 
     require_from_group: [1, ".class"] 
    } 
} 
  • primo parametro è il numero di elementi da essere richiesto.
  • Il secondo parametro è lo class assegnato a tutti gli elementi nel raggruppamento. Ho aggiunto una classe send ai tuoi due elementi di input.

  • Utilizzare anche the groups option per consolidare i due messaggi in uno solo.

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.") 
    }); 

}); 

lavoro Demo: http://jsfiddle.net/sgmvY/1/


EDIT: As per Github, there is an open issue con il metodo require_from_group. Fino a quando non viene risolto, lo sviluppatore consiglia questa soluzione di seguito. Dal momento che dovresti aggiungere manualmente il metodo rivisto nel tuo codice, non è necessario includere il file additional-methods.js.

Nuovo lavoro Demo: 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

scusa per la risposta tardiva, .... grazie per la tua risposta. Prima una cosa: posso scrivilo come una funzione, quindi verrà chiamato in una convalida jquery. come 1> function validateUser() then 2> inside of $ (document) .ready (function() {// validateUSer();} – bigZero

+0

@bigZero, 'validate()' è solo il modo in cui il plugin è inizializzato. punta a metterlo in un'altra funzione.Se vuoi _testare la validità_ del tuo modulo all'interno di una funzione, semplicemente [usa 'valid()'] (http://docs.jquery.com/Plugins/Validation/valid) in qualsiasi momento dopo l'inizializzazione del plugin. – Sparky

0

@Sparky Sto provando ad usare la tua risposta per convalidare l'aggiornamento di un nome account e/o password. Inserisco il nome e la password dell'account originale, quindi clicco sul pulsante di aggiornamento e viene eseguita la convalida del nome account e della password originali (ad esempio, nessun messaggio per indicare che è necessario immettere un nuovo account o una password). Il mio codice è:

$(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 
Problemi correlati