Javascript 使用验证器 jQuery 在 Click 事件上验证表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7445423/
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-24 02:19:08  来源:igfitidea点击:

Validate a form on Click event with validator jQuery

javascriptjqueryclicksubmitvalidation

提问by novellino

I am using jQuery validate for validate an input. My code:

我正在使用 jQuery 验证来验证输入。我的代码:

 $('#button').click( function() {       
    $("#form").validate({              
        rules: {
            phone: {
                required: true,
                number: true,
                rangelength: [7, 14]
            }
        }
    }); 
});

And the HTML:

和 HTML:

<form id="form" name="form" method="post" action="">
 <input id="phone" name="phone" class="required" type="text" />
 <div class="button" id="send_b">Send</div>
 </form>

This code is not working. If I add this line of jQuery

此代码不起作用。如果我添加这行 jQuery

$("#form").submit();  

inside the click event it works. But I don't want to submit the form so I want just to make the validation on click.

在点击事件中它起作用。但我不想提交表单,所以我只想在点击时进行验证。

Does anyone know how to do this?

有谁知道如何做到这一点?

回答by Jens Roland

Just add .form()to manually trigger the validation immediately (the default behavior waits for a submit event):

只需添加.form()立即手动触发验证(默认行为等待提交事件):

$('#button').click( function() {       
  $("#form").validate({              
    rules: {
      phone: {
        required: true,
        number: true,
        rangelength: [7, 14]
      }
    }
  }).form(); 
});

回答by Alex

Your code is binding a function to the clickevent of a button. What you're doing is saying "when this button is clicked, apply form validation to the form".

您的代码将一个函数绑定到click一个按钮的事件。您正在做的是说“当单击此按钮时,将表单验证应用于表单”。

This is the incorrect way to use the validation plugin (I'm assuming you're using thisvalidation plugin). Instead, you just execute the validation()method directly onto the formelement; the plugin takes care of the submitevent.

这是使用验证插件的错误方式(我假设您正在使用验证插件)。相反,您只需validation()直接在form元素上执行该方法;该插件负责处理该submit事件。

So, get rid of the clickevent binding.

所以,摆脱click事件绑定。

回答by mymotherland

Use form method form()method with your click event

form()在单击事件中使用表单方法方法