使用jQuery Validation插件来验证表单
jQuery Validation是一个用于验证表单的jQuery插件,简单易用,已经包含了16种内置的验证规则.Github上也有更多的验证规则可以使用.这都不是重点,重点是你可以轻松的定制自己的规则.
内置规则:
- required – Makes the element required.
- remote – Requests a resource to check the element for validity.
- minlength – Makes the element require a given minimum length.
- maxlength – Makes the element require a given maximum length.
- rangelength – Makes the element require a given value range.
- min – Makes the element require a given minimum.
- max – Makes the element require a given maximum.
- range – Makes the element require a given value range.
- step – Makes the element require a given step.
- email – Makes the element require a valid email
- url – Makes the element require a valid url
- date – Makes the element require a date.
- dateISO – Makes the element require an ISO date.
- number – Makes the element require a decimal number.
- digits – Makes the element require digits only.
- equalTo – Requires the element to be the same as another one
内置规则的使用
内置规则的使用非常简单:
首先将该插件的js文件包含进html文件:
xml
1 | <script src="/static/js/jquery.min.js"></script> |
然后用jQuery选择需要验证的表单,执行validate()函数即可:
xml
1 | <script> |
<!DOCTYPE HTML>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>
</body>
</html>
prolog
1 |
|
23 $("#ip_form").validate({
24 rules: {
25 ip: {
26 required: true,
27 ipv4: true,
28 },
29 netmask: {
30 required: true,
31 ipv4: true,
32 },
33 gateway: {
34 required: true,
35 ipv4: true,
36 },
37 },
38 }); //其中ip,netmask,gateway为表单项的name属性.required和ipv4是规则名.
Code
1 |
|
label.error {
margin-left: 10px;
padding-left: 5px;
padding-right: 5px;
color: #E2303A;
font-style: italic;
font: Helvetica Neue, 12px, #E2303A;
border: 1px solid #F2A9AE;
}
oxygene
1 |
|
23 $("#ip_form").validate({
24 rules: {
25 ip: {
26 required: true,
27 ipv4: true,
28 },
29 netmask: {
30 required: true,
31 ipv4: true,
32 },
33 gateway: {
34 required: true,
35 ipv4: true,
36 },
37 dns: {
38 dns: true,
39 }
40 },
41 submitHandler: function(form) {
42 ip_ok();
43 $("#ip-conf").modal('hide');
44 }
45 });
```
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 三木的技术博客!
评论
Powered By Valine
v1.5.2
v1.5.2