以编程方式显示表单默认验证状态 [英] Show form default Validation Status Programmatically

查看:86
本文介绍了以编程方式显示表单默认验证状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ajax提交表单.因此,我没有使用type=submit.我在链接(<a>)上使用onClick事件,以使用ajax发送表单数据.我还想利用HTML5表单验证功能.
因此,在发送数据之前,我使用了功能.checkValidity来检查表单的有效性.
如果返回true,则发送数据.但是,当它返回false时,我想使用HTML5默认通知方案向用户显示该表单无效.但我不知道该如何触发.

I want to submit a form using ajax. So I am not using the type=submit. I am using a onClick event on a link(<a>) to send the form data using ajax. I also want to take advantage of HTML5 form validation capabilities.
So before sending the data, I used the function .checkValidity to check the validity of the form.
If it returns true then I send the data. But when it return false I want to show user that the form is invalid using HTML5 default notifying scheme. But I don't know how to trigger that.

是否可以通过任何方式以编程方式显示验证表单.

一种方法是,如果checkValidity返回false,则触发Submit事件.但这将刷新页面.我不想更改页面的状态.

One way to do is trigger the submit event if checkValidity return false. But this will refresh the page. I don't want to change the state of the page.

checkValidity仅检查有效性并通知程序.它不会以交互方式通知用户.

checkValidity only checks validity and inform the program. It doesn't inform the user interactively.

推荐答案

如果让表单具有提交按钮并返回false,则可以执行此操作! 您可以在与非提交相同的事件处理程序中执行此操作! 因此,首先测试您是否属于表单,如果是,请使其检查有效性",并且永远不要返回true(即使有效)!

You can do it if you let your form have a submit button and return false! And you cán do it in the same event handler as the non-submits! So, first test if you are part of a form and if so, make it check Validity and never return true (even if valid)!

$('.ajx')   
    .on("submit click", function(e) {

        var $this           = $(this)

        //Force native form validating and notification
        form = $this.closest('form')[0]
        if (form) {
            //Follow through with form submit (element must be of submit type!)
            if(!form.checkValidity()) {
                //don't ask me!
                sleep(3000);
                return false
            }
        }           

        //only preventDEfault AFTER possible form element click
        e.preventDefault()

        //...your project further ajax code
        //Makes sure your form never submits
        if (e.type=='submit') return false
}

小缺点:您必须在提交"按钮上执行此操作,但是始终可以将<a>更改为type=submit.但是,您不必更改非形式<a>的内容!

Small downside: You have to do this on the submit button, but it's always possible to change your <a> into type=submit. You don't have to change the non form <a>'s though!

这篇关于以编程方式显示表单默认验证状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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