手动调用HTML5表单验证 [英] Manually invoke HTML5 form validation

查看:100
本文介绍了手动调用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>

这篇关于手动调用HTML5表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆