0

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.

2
  • 1
    IDs should be unique. Having two inputs with the id from-email is not valid Commented Nov 14, 2017 at 16:19
  • Do these forms have <form> tags? Commented Nov 14, 2017 at 16:21

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Gotcha. Yeah, I might need to add an iterator when the form gets generated. But in the case of adding the specific class name to the parents, it worked. Thanks!
0

Just add required> attribute and add this js

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.