手动调用HTML5表单验证

手动调用HTML5表单验证

问题描述:

我有一个遗留表单,我正在尝试更新以进行简单的HTML5表单验证。

I have a legacy form that I'm trying to update to do simple HTML5 form validation.

目前,它使用reCaptcha,并调用verify()函数在转发表单内容之前验证reCaptcha质询。我想确保表单在继续reCaptcha处理之前通过HTML5验证,并显示浏览器默认使用的相应错误消息。

Currently, it uses reCaptcha, and invokes a verify() function that validates the reCaptcha challenge before forwarding the contents of the form. I would like to ensure that the form passes HTML5 validation before continuing with the reCaptcha processing, and display the appropriate error messages that the browser would use by default.

包含iframe形式为<!DOCTYPE html> DOCTYPE。输入字段具有必需属性。

The iframe containing the form as the <!DOCTYPE html> doctype. The input fields have the required attribute.

提交按钮具有以下内容:

The submit button has the following:

<input type="button" id="script_send" onclick="javascript:verify(this.form);" value="ENVIAR">

验证脚本具有基本结构。

The verify script has the basic structure.

function verify(theForm) {
    form = theForm;

    /* Recaptcha processing */
}

我试过使用

if (!form.checkValidity()) {
    return false;
}

即使表单未提交,我也没有显示错误屏幕,显示用户应该提供哪些字段。

and even though the form was not submitted, I get no errors displayed on the screen, showing the user what fields they should be providing.

我已经看到这个jsfiddle [http://jsfiddle.net/5ycZz/]用于演示checkValidity( )功能,但即便没有显示我希望在Chrome,IE10或FF中看到的视觉错误提示。

I have seen this jsfiddle [http://jsfiddle.net/5ycZz/] used to demonstrate the checkValidity() function, but even that does not display the visual error cues that I would expect to see, in Chrome, IE10 or FF.

尝试在表单上设置提交事件,而不是在提交按钮上设置单击操作。 提交事件在验证后触发,因此只有在传递所有其他约束时才会发生。这也意味着您不必在验证函数中调用 form.checkValidity()

Try setting the submit event on the form instead of putting a click action on the submit button. The submit event fires AFTER validation so it should only happen if all other constraints passed. This also means you wont have to call form.checkValidity() in your verify function.

<form onsubmit="verify(this)">
...
</form>