html5 表单验证、无效表单操作并在所有 html5 表单元素都经过验证时执行 jQuery?

html5 表单验证、无效表单操作并在所有 html5 表单元素都经过验证时执行 jQuery?

问题描述:

我有一个简单的 HTML5 表单,我想利用它进行必填字段验证.我的问题是我想使用 HTML5 表单验证,但同时避免实际提交表单,因为我想执行 jQuery ajax 调用.我知道您可以禁用 html5 验证,但我想将此作为我的主要表单验证方法而不是 jQuery 插件.

I have a simple HTML5 form that I want to leverage for required field validation. My issue is that I want to use the HTML5 form validation BUT at the same time avoid actually submitting the form because I want to execute a jQuery ajax call instead. I know you can disable html5 validation, but I want to keep this as my primary method of form validation instead of a jQuery plugin.

有什么想法吗?

HTML

<form action="donothing" id="membershipform" method="get" accept-charset="utf-8">
    <input type="text" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="first and last name" required>
    <input type="email" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="email" required>
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="phone" required>    
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="mailing address" required>      
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="how you heard about us" required>
    <p>
        <input type="submit" id="submitbtn" class="submitbtn" value="Continue" style="width:265px">
    </p>
</form> 

JAVASCRIPT:

$(function(){
  $("#submitbtn").click(function(){
    $.ajax({
      url: "<?php bloginfo('template_url') ?>/ajax-membership.php",
      success: 
      function(txt){
        if(txt){
          $("#thankyou").slideDown("slow");
        }
      }
    });
  });
});

根据这个:是否有任何浏览器支持 HTML5 的 checkValidity() 方法?,这可能不是最新的事实,因为 HTML5 正在进行中,Form.checkValidity()element.validity.valid 应该让你从 JavaScript 访问验证信息.假设这是真的,您的 jQuery 需要将自身附加到表单提交并使用它:

According to this: Do any browsers yet support HTML5's checkValidity() method?, and this may not be the latest truth since HTML5 is a work in progress, the Form.checkValidity() and element.validity.valid should let you access validation information from JavaScript. Assuming that's true, your jQuery would need to attach itself to the form submit and make use of that:

$('#membershipform').submit(function(event){
    // cancels the form submission
    event.preventDefault();

    // do whatever you want here
});