[英]JQuery form validation rules syntax
I'm trying to use jquery validation with a rule/message set and can't seem to get it working. 我正在尝试将jquery验证与规则/消息集一起使用,但似乎无法使其正常工作。 Relativeny new to JQuery, so apologies if it's a basic question.
相对于JQuery而言,这是一个相对较新的问题,如果这是一个基本问题,则表示歉意。 I'm trying to use document.forms[0] instead of a form ID.
我正在尝试使用document.forms [0]代替表单ID。 It works with simple validation where the field has class="required" but not if I try to introduce rules.
它与简单验证一起使用,其中字段具有class =“ required”,但如果我尝试引入规则则不行。 Any help greatly appreciated.
任何帮助,不胜感激。 Here's the code:
这是代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery- validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$(document.forms[0]).validate({
rules: {
cname: {
required: true,
}
},
messages: {
cname: "Please enter a valid Name."
},
});
});
</script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name"/>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
I suppose I'll answer the question since my comment was correct. 我想我会回答这个问题,因为我的评论是正确的。
Try putting the name
attribute as "cname" as well. 尝试将
name
属性也设置为“ cname”。 The validator looks for the name
attribute. 验证器查找
name
属性。
Firstly, you can just target your form by its id
, #commentForm
. 首先,您可以通过其
id
#commentForm
定位表单。 Secondly, the root cause of your problem was that you were improperly targeting the input
field by its id
attribute. 其次,问题的根本原因是您没有通过
input
字段的id
属性来正确定向input
字段。 However, the .validate()
plugin is looking for the name
attribute, which in your case, also happened to be "name"
. 但是,
.validate()
插件正在寻找name
属性,在您的情况下,该属性也恰好是"name"
。 I've changed the value of the name
attribute in my example below just to make it more clear. 我在下面的示例中更改了
name
属性的值,只是为了使其更加清楚。
jQuery: jQuery的:
$(document).ready(function(){
$('#commentForm').validate({
rules: {
username: {
required: true
}
},
messages: {
username: "Please enter a valid Name."
}
});
});
HTML: HTML:
<form class="cmxform" id="commentForm" method="get" action="">
<input type="text" id="cname" name="username" />
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.