首页 > 解决方案 > 如何在 HTML 5 验证之前使用 jquery 验证表单

问题描述

我有一个阿拉伯语的表格,我尝试用两种方式验证它:html 5 和 j 查询。问题是英文 HTML 5 警报出现在第一个出现之前,阿拉伯语 j 查询警报出现,但在我的情况下,我想要相反的一些变化。我希望阿拉伯语 j 查询警报出现在第一个,并且 HTML 5 英语警报仅在 j 查询无法阻止用户作弊时出现..提前致谢

<!DOCTYPE HTML>
<html>
<head>
<title>j query_validation</title>
<meta charset="UTF-8">
</head>

<body>
<form id="formId">
<input type="text" class="input-string" required/>
<input type="submit"/>
<p class="alert-error" style="display: 
none">can't be empty</p>
</form>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
 <script>
 $('#formId').submit(function(e){
 var inputValue = $('.input-string').val().length;
 if(inputValue == 0)
 {
    $('.alert-error').show();
    e.preventDefault();
}
});

</script>
</body>

</html>

标签: jqueryhtml

解决方案


只需将 e.preventDefault() 放在函数的开头即可。

这可以防止任何默认的表单提交行为。如果成功,请记住实际提交表单。

$('#formId').submit(function(e){
 e.preventDefault();
 var inputValue;
 $('.input-string').each(function(){ // If you're checking for class, you may want to include this .each function, as many elements can have the same class. If you switch to ID, this can be removed.
 inputValue += $(this).val().length;
     }); // End .each

 if(inputValue == 0){        
    $('.alert-error').show();        
    }
 else{
    $('.alert-error').hide(); // Not really necessary if you're submitting and refreshing anyway, but it lets the user know it will be submitted successfully, before the page actually refreshed.
    form.submit();
    }

}); // End .submit

编辑:下面附上我的完整答案,根据 OP 的要求,以满足评论中的进一步要求。

<!DOCTYPE HTML>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <title>j query_validation</title>
  <meta charset="UTF-8">
</head>

<body>
  <form id="formId">
    <input type="text" class="input-string" required/>
    <button id="test-button" type="button" role="button">Test Me </button>
    <p class="alert-error" style="display: 
none">can't be empty</p>
  </form>

  <script>
    $('#test-button').click(function(e) {
      e.preventDefault();
      var inputValue = 0;
      $('.input-string').each(function() { // If you're checking for class, you may want to include this .each function, as many elements can have the same class. If you switch to ID, this can be removed.
        inputValue += $(this).val().length;
      }); // End .each
      // inputValue = 0; 
      if (inputValue == 0) {
        $('.alert-error').each(function() {
          $(this).css("display", "block");
        });
      } else {
        $('.alert-error').each(function() {
          $(this).css("display", "none"); // Not really necessary if you're submitting and refreshing anyway, but it lets the user know it will be submitted successfully, before the page actually refreshed.
        });

        $("#formId").submit();
      }

    }); // End .submit
  </script>
</body>

</html>


推荐阅读