gpt4 book ai didi

JQuery 表单验证规则语法

转载 作者:行者123 更新时间:2023-12-01 03:17:33 24 4
gpt4 key购买 nike

我正在尝试将 jquery 验证与规则/消息集一起使用,但似乎无法使其工作。对于 JQuery 来说相对较新,所以如果这是一个基本问题,我们深表歉意。我正在尝试使用 document.forms[0] 而不是表单 ID。它适用于简单的验证,其中字段具有 class="required",但如果我尝试引入规则则不会。非常感谢任何帮助。代码如下:

<!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>

最佳答案

首先,您可以通过表单的 id#commentForm 来定位表单。其次,问题的根本原因是您通过 id 属性错误地定位了 input 字段。但是, .validate() 插件正在寻找 name 属性,在您的情况下,该属性也恰好是 "name"。我在下面的示例中更改了 name 属性的值,只是为了使其更加清晰。

jQuery:

$(document).ready(function(){
$('#commentForm').validate({
rules: {
username: {
required: true
}
},
messages: {
username: "Please enter a valid Name."
}
});
});

HTML:

<form class="cmxform" id="commentForm" method="get" action="">

<input type="text" id="cname" name="username" />

....

<强> Working DEMO:

http://jsfiddle.net/egdEn/

See the online documentation for more info.

关于JQuery 表单验证规则语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13937401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com