2013-02-28 11 views
7

Chcę sprawdzić poprawność mojego formularza, tak aby zawierał dwa puste pola, co najmniej jedno pole musi być wypełnione, a także dwa pola wypełniony; ale nie można zostawić żadnego pola pustego.jQuery Validate, z dwóch pustych pól, musi być wypełnione co najmniej jedno pole lub oba

Używam jquery-1.9.1-min.js i tutaj jest moja strona 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> 

Wszelkie sugestie, jak to zrobić ...?

sofar Próbowałem

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

wciąż nie wyjście friutful.

+0

Czy zawiera Pan wtyczkę jQuery Validate? Ponieważ używasz 'validator.addMethod()', to wymaga, aby wtyczka jQuery Validate została dołączona i poprawnie skonfigurowana. – Sparky

+0

Prosimy nie nadużywać SO, publikując zduplikowane pytania: [Sprawdź poprawność (w kategoriach puste pole) dowolne z dwóch pól w 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

Odpowiedz

17

Próbujesz użyć validator.addMethod, który jest częścią the jQuery Validate plugin. Musisz dodać tę wtyczkę do kodu, jeśli jeszcze tego nie zrobiłeś.

Następnie użyj reguły require_from_group, która jest już częścią the Validate plugin's additional-methods.js file. (Nie zapomnij dołączyć plik additional-methods.js zbyt.)

rules: { 
    myfieldname: { 
     require_from_group: [1, ".class"] 
    } 
} 
  • Pierwszy parametr jest liczbą elementów, aby być wymagane.
  • Drugi parametr to class przypisany do wszystkich elementów w twoim grupowaniu. Dodałem klasę send do twoich dwóch elementów wejściowych.

  • Użyj także the groups option, aby skonsolidować dwie wiadomości w jedną.

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

}); 

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


EDIT: As per Github, there is an open issue metodą require_from_group. Dopóki nie zostanie naprawiony, programista zaleca to rozwiązanie poniżej. Ponieważ ręcznie dodajesz poprawioną metodę do kodu, nie ma potrzeby dołączania pliku additional-methods.js.

New Demo pracy: 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

Przepraszam za spóźnioną odpowiedź, .... dziękuję za odpowiedź. Jedną rzecz: czy mogę zapisz to jako funkcję, a następnie zostanie wywołane w walidacji jquery. jak 1> function validateUser() następnie 2> wewnątrz $ (document) .ready (function() {// validateUSer();} – bigZero

+0

@bigZero, 'validate()' to tylko jak inicjalizowana jest wtyczka. wskaż w umieszczeniu go w innej funkcji .Jeśli chcesz \ testować poprawność_ twojej formy w funkcji, po prostu [użyj 'valid()'] (http://docs.jquery.com/Plugins/Validation/valid) w dowolnym momencie po inicjalizacji wtyczki. – Sparky

0

@Sparky Staram się wykorzystywać swoją odpowiedź do sprawdzania aktualizacji nazwy konta i/lub hasło. Wprowadzam oryginalną nazwę konta i hasło, a następnie klikam przycisk aktualizacji i przeprowadzana jest walidacja pierwotnej nazwy konta i hasła (tzn. Nie ma komunikatu informującego, że konieczne jest wprowadzenie nowego konta lub hasła). Mój kod to:

$(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 
Powiązane problemy