【问题标题】:Why is all validation happening at one time为什么所有验证都同时发生
【发布时间】:2017-10-20 18:25:09
【问题描述】:

这是 jquery 脚本。验证有效,但是如果您将一个字段留空,然后在表单上单击该字段,则表单中每个字段的所有验证消息都会显示,而不仅仅是空的字段。以及如何以我的示例中的格式验证 jquery 中的电子邮件地址?有人有什么想法吗?感谢您提前提供任何帮助

$(document).ready(function() {
$('#firstname').on('blur', function() {
    if ($('#firstname').val() == '') {
        $('.errorMsg').show();
    } else {
        $('.errorMsg').hide();
    }
    });
     $('#lastname').on('blur', function() {
    if ($('#lastname').val() == '') {
        $('.errorMsg').show();
    } else {
        $('.errorMsg').hide();
    }
    });
     $('#email').on('blur', function() {
    if ($('#email').val() == '') {
        $('.errorMsg').show();
    } else {
        $('.errorMsg').hide();
    }
    });
    $('#roomtype').on('blur', function() {
    if ($('#roomtype').val() == '') {
        $('.errorMsg').show();
    } else {
        $('.errorMsg').hide();
    }
    });
});

【问题讨论】:

  • 你的 html 是什么?
  • First name required 在表单中,firstname、lastname、email 和 roomtype 都是这样的,只是 id 和 label 相应地改变了

标签: jquery html validation


【解决方案1】:

因为您使用的是 $('.errorMsg').show();,它将针对名称 = errorMsg 的所有类。

确保每个验证只针对唯一的错误消息

对每个输入使用$(this).next(".errorMsg").show();$(this).next(".errorMsg").hide();

示例:

   if ($('#email').val() == '') {
        $(this).next(".errorMsg").show();
   } else {
        $(this).next(".errorMsg").hide();
   }

电子邮件验证示例:

$('.errorMsg').hide();

$('#email').on('blur', function(event) {
  if (event.target.checkValidity()){
    $(this).next('.errorMsg').hide();
  } else {
    $(this).next('.errorMsg').show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="myform">
  <input id="email" type="email" placeholder="your email">
  <span class="errorMsg">Not Valid!!!!!!!!!!!</span>
</form>

【讨论】:

  • 这行得通,谢谢。您知道我如何向电子邮件地址添加适当的验证,以便它需要采用正确的格式吗?
  • @Smith 不要关闭输入标签,有些标签是禁止关闭的:img, input, br, hr, meta
  • @Smith &lt;input type="email" placeholder="your email"&gt;
  • 我有 但它仍然像文本字段一样进行验证。例如,当其中有任何字母时,它是有效的
猜你喜欢
  • 1970-01-01
  • 2016-04-29
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多