简体   繁体   English

jQuery验证相似形式的单个输入

[英]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: 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: 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. 您将from-email的ID加倍了,这就是为什么。 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. 在您的JS中,您正在检查ID为from-email所有字段,在这种情况下,由于两个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. 如果其中之一是错误的,则您将在所有父母中搜索email-error ,这些email-error将上升到正文,然后从错误包装程序中查找所有错误。 $this.parents(“.general-form“) will do the deal and only go up to the wrapper of the input and error in your case. $this.parents(“.general-form“)会处理这笔交易,并且只会转到您的情况下输入和错误的包装。

Always make sure your id's are unique. 始终确保您的ID是唯一的。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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