单击按钮时进行jQuery表单验证 [英] jQuery form validation on button click
问题描述
我有一个简单的页面,其中包含一个表单和一个位于表单外部的按钮.我正在尝试单击按钮时验证表单. 我在document.onready函数上添加了验证表单的规则.但是,该表单尚未得到验证.
I have a simple page with a form and a button outside the form. I am trying to validate the form on the button click. I have added the rules for validation of the form on the document.onready function. However the form is not getting validated.
HTML:-
<html>
<head>
<script src="lib/jquery1.5.2.js"></script>
<script src="lib/jquery.validate.js"></script>
<script src="lib/myjs.js"></script>
</head>
<body>
<form id="form1" name="form1">
Field 1: <input id="field1" type="text" class="required">
</form>
<div>
<input id="btn" type="button" value="Validate">
</div>
</body>
</html>
JS:-
$(document).ready(function(){
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
$('#btn').click(function() {
$("#form1").validate(); // This is not working and is not validating the form
});
});
你知道怎么了吗?
推荐答案
在您的click
处理程序中,错误是.validate()
方法;它只会初始化插件,不会验证form
.
Within your click
handler, the mistake is the .validate()
method; it only initializes the plugin, it does not validate the form
.
要消除在form
中没有submit
按钮的需要,请使用.valid()
触发验证检查...
To eliminate the need to have a submit
button within the form
, use .valid()
to trigger a validation check...
$('#btn').on('click', function() {
$("#form1").valid();
});
.validate()
-在DOM就绪时初始化一次插件(带有选项).
.validate()
- to initialize the plugin (with options) once on DOM ready.
.valid()
-随时检查验证状态(布尔值)或触发对form
的验证测试.
.valid()
- to check validation state (boolean value) or to trigger a validation test on the form
at any time.
否则,如果在form
容器中有一个type="submit"
按钮,则不需要特殊的click
处理程序和.valid()
方法,因为该插件会自动捕获它.
Otherwise, if you had a type="submit"
button within the form
container, you would not need a special click
handler and the .valid()
method, as the plugin would capture that automatically.
编辑:
您的HTML中也有两个问题...
You also have two issues within your HTML...
<input id="field1" type="text" class="required">
-
在
.validate()
中声明规则时不需要class="required"
.这是多余的和多余的.You don't need
class="required"
when declaring rules within.validate()
. It's redundant and superfluous.缺少
name
属性.规则在.validate()
中由name
声明.该插件依赖于唯一的name
属性来跟踪输入.The
name
attribute is missing. Rules are declared within.validate()
by theirname
. The plugin depends upon uniquename
attributes to keep track of the inputs.应该是...
<input name="field1" id="field1" type="text" />
这篇关于单击按钮时进行jQuery表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!