How can I check the validity of an HTML5 form that does not contain a submit button?

后端 未结 2 2014
臣服心动
臣服心动 2020-12-05 13:01

I have the following code example that works in browsers that check when they see the HTML5 \"required\" on an input like the email here:

相关标签:
2条回答
  • 2020-12-05 13:46

    In HTML5, you may use a "form" attribute on an element to explicitly associate it with a Form element regardless of where it is positioned in the page structure: http://developers.whatwg.org/association-of-controls-and-forms.html#attr-fae-form

    In compliant browsers, you ought to be able to put your input[type=submit][form=id] element anywhere and still have it properly trigger the validation and submission process.

    I tend to put code that is supposed to intercept the submission process in the form's "submit" event handler, that way it is triggered by users hitting the Enter key as well as any input[type=submit] buttons I have.

    0 讨论(0)
  • 2020-12-05 13:54

    Assuming that you have set the form element to an object called $form, then if (!$form.valid || $form.valid()) is clever syntax that means "if $form doesn't have a method called valid, or if valid() returns true". Typically you will have installed and initialized the jQuery Validation plugin by then, but this prevents the form from becoming disabled if the validation plugin is not loaded.

    You can do a similar test using the HTML5 method checkValidity, looking something like this:

    if (!$form.checkValidity || $form.checkValidity()) {
      /* submit the form */
    }
    

    EDIT: checkValidity is a function from the HTML5 forms spec. As of February 2016 CanIUse.com reports that over 95% of browsers support it.

    0 讨论(0)
提交回复
热议问题