使用 JQuery 验证验证字段而不提交任何内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18220340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:13:20  来源:igfitidea点击:

Validate fields using JQuery validation without any submit?

jqueryjquery-validate

提问by David Bridgeland

I have a HTML5 web application with numerous user-entered fields, and I would like to do some client-side validation on those fields in javascript before sending them to the server. Easy right? Just use JQuery validation plugin --- http://jqueryvalidation.org/

我有一个包含大量用户输入字段的 HTML5 Web 应用程序,我想在将它们发送到服务器之前对 javascript 中的这些字段进行一些客户端验证。容易吧?只需使用 JQuery 验证插件 --- http://jqueryvalidation.org/

But there's a catch. My web app has no forms. There is no submit anywhere in the HTML. Instead there's a JQuery change handler on every user-changeable element, and when the user changes the value of one of those element, an AJAX call is made. (This nonstandard user interaction architecture makes sense for this application.)

但有一个问题。我的网络应用程序没有表单。HTML 中的任何地方都没有提交。相反,每个用户可更改的元素都有一个 JQuery 更改处理程序,当用户更改其中一个元素的值时,会进行 AJAX 调用。(这种非标准的用户交互架构对这个应用程序很有意义。)

I would like to validate the field before the AJAX call, and use the JQuery validation plugin to do that. But I can't figure out how.

我想在 AJAX 调用之前验证该字段,并使用 JQuery 验证插件来做到这一点。但我无法弄清楚如何。

Is it possible to use the JQuery validation plugin without a submit anywhere? How would I do this? Or is another approach better?

是否可以在任何地方不提交的情况下使用 JQuery 验证插件?我该怎么做?或者另一种方法更好?

回答by Sparky

Firstly, and most importantly, you mustwrap your input elements inside <form></form>tags for the jQuery Validate plugin to operate. However, a submit button is not required.

首先,也是最重要的一点,您必须将输入元素包装在<form></form>标签内,以便 jQuery Validate 插件运行。但是,不需要提交按钮。

Secondly, you can programatically trigger the validity test of any or all elements without a submit button by using the .valid()method.

其次,你可以通过编程方式使用触发任何或所有元素没有一个提交按钮的有效性检验.valid()方法

$(document).ready(function() {

    $('#myform').validate({  // initialize the plugin on your form.
        // rules, options, and/or callback functions
    });

    // trigger validity test of any element using the .valid() method.
    $('#myelement').valid();

    // trigger validity test of the entire form using the .valid() method.
    $('#myform').valid();

    // the .valid() method also returns a boolean...
    if ($('#myform').valid()) {
        // something to do if form is valid
    }

});

DEMO: http://jsfiddle.net/URQGG/

演示http: //jsfiddle.net/URQGG/

回答by plalx

You will have to wrap your fields within a form to use the validation plugin and it's a good practiceanyway. Also, you can invoke the plugin's validation programmatically and check if the form is valid by doing:

您必须将字段包装在表单中才能使用验证插件,无论如何这是一个很好的做法。此外,您可以以编程方式调用插件的验证并通过执行以下操作检查表单是否有效:

var $form = $('#your_form'),
    validator = $form.validate({...});

//validate the form
validator.form();

//check if the form is valid 
if ($form.valid()) {
    //form is valid
}

For more options, have a look at the docs.

有关更多选项,请查看文档

回答by Simon Ludwig

I've created a little helper. Just add this line of code and then you can use any button anywhere.

我创建了一个小帮手。只需添加这行代码,然后您就可以在任何地方使用任何按钮。

$("body [data-submit-form]").on("click", function (event) {
    $("#" + $(event.target).data('submit-form')).valid();
});

<form id="component-form">

</form>

<button data-submit-form="component-form">Button</button>

Explanation: The jquery code listens for all clicks on an element with the attribute 'data-submit-form', in the listener the data-attribute gets extracted and then i trigger the valid method on the matching form.

说明:jquery 代码侦听具有“data-submit-form”属性的元素上的所有点击,在侦听器中提取数据属性,然后触发匹配表单上的有效方法。

NOTE: if you want to submit the form if the form is valid use this code:

注意:如果您想在表单有效的情况下提交表单,请使用以下代码:

$("body [data-submit-form]").on("click", function (event) {
    var form = $("#" + $(event.target).data('submit-form'));
    if (form.valid()) {
        form.submit();
    }
});

回答by Mohit Miglani

Use this code for two sample fields email and password:-

将此代码用于两个示例字段电子邮件和密码:-

<head>
    <script src="jquery-3.4.0.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #txt1{

        margin-left:23px;
        border-radius: 12px;
       }
       #txt2{
        border-radius: 12px;
       }
       #btn1{
        border-radius: 12px;
        width: 8em;  height: 2em;
        cursor:pointer;
        background-color: #008CBA;
       }
       #lbl1,#lbl2{
        font-family: "Comic Sans MS", cursive, sans-serif;
        color:red;
       }
    </style>
</head>

<body>
    <div class="container">
        <form>
            <center> <label id="lbl1">Email: </label><input type="text" id="txt1"></center></input><br>
            <center><label id="lbl2">Password: </label><input type="password" id="txt2"></center></input>
            <br><br>
            <center><input type="button" id="btn1" name="btn1" value="Login" style="color:darkblue;font-size:15px;"></center></input>
        </form>

    </div>
    <script>
        $(document).ready(function () {
            $('#btn1').click(function () {
                var email = $('#txt1').val();
                var pass = $('#txt2').val();
                if (email == '') {
                    $('input[type="text"]').css("border", "2px solid red");
                    $("#txt1").parent().after("<div class='validation' style='color:red;margin-left:93px;'><center>Please enter email address</center></div>");
                    alert("hi");
                }
                else {

                }
                if (pass == '') {
                    $('input[type="password"]').css("border", "2px solid red");
                    $("#txt2").parent().after("<div class='validationp' style='color:red;margin-left:70px;'><center>Please enter password</center></div>");
                }
                $('input[type="text"]').keydown(function () {
                    $('input[type="text"]').css("border", "");
                    $(".validation").remove();
                });
                $('input[type="password"]').keydown(function () {
                    $('input[type="password"]').css("border", "");
                    $(".validationp").remove();

                });

            });
        });

    </script>
</body>

</html>

回答by Rejeesh

Just call the form submit method using jquery

只需使用调用表单提交方法 jquery

$("#formId").submit()

This will validate entire form, same as when we click the submit button

这将验证整个表单,就像我们点击提交按钮一样