简体   繁体   中英

jQuery Validation for Multiple Dynamic Username / Password Fields

There's a button that adds additional username and password fields when clicked. The fields end up having name and field IDs in increments of 3, ie user6, user9, user12... Having trouble figuring out how to validate for required and minlength with the jQuery Validation plugin. Here is the code that dynamically creates those fields (I did not write).

$(document).on('click', '#add', function(e) {
  var intId = $("#the_form div").length + 1;
  var userWrapper = $("<div class=\"form-group userwrapper\" id=\"field" + intId + "\"/>");
  var userDiv = $("<div class=\"col-lg-4\">");
  var newUserLabel = $("<label class=\" control-label\" for=\"user" + intId + "\">User:</label>");
  var newUser = $("<input type=\"text\" minlength=\"2\" what=\"users\" class=\"form-control users\" name=\"user" + intId + "\" id=\"user" + intId + "\" /></div>");
  var passDiv = $("<div class=\"col-lg-4\">");
  var newPassLabel = $("<label class=\"control-label\" for=\"passUser" + intId + "\">Password:</label>");
  var newPass = $("<input minlength=\"6\" type=\"password\" what=\"passes\" class=\"form-control passes\" name=\"pass" + intId + "\" id=\"passUser" + intId + "\" />");
  var removeButton = $("<input type=\"button\" class=\"remove btn btn-danger\" aria-hidden=\"true\" value=\"&times;\"/>");
  removeButton.click(function() {
    $(this).parent().prev().remove();
    $(this).parent().remove();
  });
  userDiv.append(newUserLabel);
  userDiv.append(newUser);
  passDiv.append(newPassLabel);
  passDiv.append(newPass);
  passDiv.append(removeButton);
  userWrapper.append(userDiv);
  userWrapper.append(passDiv);
  $("#the_form").append(userWrapper);});

Take a look at the following fiddle: http://jsfiddle.net/yvanavermaet/v5Vvs/

Steps to make it work: - Added "require" class to the input fields (you've already added the minlength validation) - Called the validate function on the form to activate the validation on submit (standard behaviour)

$("#the_form").validate();

Is this what you were looking for? If not, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM