简体   繁体   中英

jQuery validate single input in similar forms

I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.

HTML:

<div class="general-form">
  <div class="email-error" style="display:none;">
    <p>You need valid email</p>
  </div>
  <div class="form-wrap">
    <div class="form-row">
      <input id="from-email" type="email" name="email" placeholder="Your Email" />
    </div>
    <div class="btn-row">
      <button class="submit-btn">Submit</button>
    </div>
  </div>
</div>

<div class="general-form">
  <div class="email-error" style="display:none;">
    <p>You need valid email</p>
  </div>
  <div class="form-wrap">
    <div class="form-row">
      <input id="from-email" type="email" name="email" placeholder="Your Email" />
    </div>
    <div class="btn-row">
      <button class="submit-btn">Submit</button>
    </div>
  </div>
</div>

JS:

$(".submit-btn").on("click", function() {
  var $this = $(this);
  var valid_email = $this.find("#from-email").val();
  if (/(.+)@(.+){2,}\.(.+){2,}/.test(valid_email)) {
    return true;
  } else {
    $this.parents().find(".email-error").show();
    return false;
  }
});

Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.

You doubled the id from-email that's why. In your JS you are checking all fields with the id from-email in this case both of the inputs are checked because both the id.

If one of them is wrong you are searching for the email-error in all of your parents which will go up to the body and then find all off the error wrappers. $this.parents(“.general-form“) will do the deal and only go up to the wrapper of the input and error in your case.

Always make sure your id's are unique.

只需添加required>属性并添加此js

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

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