我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。

我想在不提交表单的情况下触发验证。这可能吗?


当前回答

这是让HTML5对任何表单执行验证的一种非常直接的方式,同时仍然拥有对表单的现代JS控制。唯一需要注意的是提交按钮必须在<form>内。

html

<form id="newUserForm" name="create">
Email<input type="email" name="username" id="username" size="25" required>
Phone<input type="tel" id="phone" name="phone" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" size="12" maxlength="12" required>
<input id="submit" type="submit" value="Create Account" >
</form>

js

// bind in ready() function
jQuery( "#submit" ).click( newAcctSubmit );

function newAcctSubmit()
{
  var myForm = jQuery( "#newUserForm" );

  // html 5 is doing the form validation for us,
  // so no need here (but backend will need to still for security)
  if ( ! myForm[0].checkValidity() )
  {
    // bonk! failed to validate, so return true which lets the
    // browser show native validation messages to the user
    return true;
  }

  // post form with jQuery or whatever you want to do with a valid form!
  var formVars = myForm.serialize();
  etc...
}

其他回答

我知道这个问题已经有了答案,但我还有另一个可能的解决方案。

如果使用jquery,你可以做到这一点。

首先在jquery上创建两个扩展,这样你就可以在需要时重用它们。

$.extend({
    bypassDefaultSubmit: function (formName, newSubmitMethod) {
        $('#'+formName).submit(function (event) {
            newSubmitMethod();
            event.preventDefault();
        }
    }
});

接下来,在你想使用它的地方做一些这样的事情。

<script type="text/javascript">
    /*if you want to validate the form on a submit call, 
      and you never want the form to be submitted via
      a normal submit operation, or maybe you want handle it.
    */
    $(function () {
        $.bypassDefaultSubmit('form1', submit);
    });
    function submit(){ 
        //do something, or nothing if you just want the validation
    }

</script>

我认为这是最好的方法

将使用jQuery验证插件,使用最佳实践的表单验证,它也有良好的浏览器支持。因此,您不必担心浏览器兼容性问题。

并且我们可以使用jQuery验证valid()函数来检查所选表单是否有效,或者是否所有所选元素都有效,而无需提交表单。

<form id="myform">
   <input type="text" name="name" required>
   <br>
   <button type="button">Validate!</button>
</form>
<script>
  var form = $( "#myform" );
  form.validate();
  $( "button" ).click(function() {
    console.log( "Valid: " + form.valid() );
  });
</script>
$(document).on("submit", false);

submitButton.click(function(e) {
    if (form.checkValidity()) {
        form.submit();
    }
});

我找到了一个适合我的方法。 只需要像这样调用一个javascript函数:

action=“javascript:myFunction();”

然后是html5验证……真的很简单:-)

根据这个问题,html5的有效性首先应该使用jQuery进行验证,在大多数答案中,这是不会发生的,原因如下:

同时使用html5表单的默认函数进行验证

checkValidity();// returns true/false

我们需要理解jQuery返回对象数组,而选择像这样

$("#myForm")

因此,您需要指定第一个索引以使checkValidity()函数工作

$('#myForm')[0].checkValidity()

以下是完整的解决方案:

<button type="button" name="button" onclick="saveData()">Save</button>

function saveData()
{
    if($('#myForm')[0].checkValidity()){
        $.ajax({
          type: "POST",
          url: "save.php",
          data: data,
          success: function(resp){console.log("Response: "+resp);}
        });
    }
}