jQuery验证插件validation使用指南
jQuery验证插件validation是一款简单易用的表单验证插件,可以有效地满足开发人员对于表单的验证需求。
安装
<!-- 引入 jQuery -->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<!-- 引入 jQuery validation 插件 -->
<script src="https://cdn.bootcss.com/jquery-validate/1.19.0/jquery.validate.min.js"></script>
使用方法
基本使用
<form id="myform">
<label for="field">Required:</label>
<input class="left" id="field" name="field" />
<br/>
<label for="password">Password:</label>
<input class="left" id="password" name="password" type="password" />
<br/>
<label for="password">Confirm Password:</label>
<input class="left" id="confirm_password" name="confirm_password" type="password" />
<br/>
<input class="submit" type="submit" value="Submit"/>
</form>
<script>
$(document).ready(function(){
// 初始化表单验证插件
$("#myform").validate({
// 设置验证规则
rules: {
field: {
required: true, // 必填
minlength: 2 // 最少2个字符
},
password: {
required: true, // 必填
minlength: 6 // 最少6个字符
},
confirm_password: {
required: true, // 必填
minlength: 6, // 最少6个字符
equalTo: "#password" // 与#password的值相同
}
},
// 设置提示信息
messages: {
field: {
required: "This field is required.",
minlength: "Please enter at least 2 characters."
},
password: {
required: "Password is required.",
minlength: "Please enter at least 6 characters."
},
confirm_password: {
required: "Please confirm password.",
minlength: "Please enter at least 6 characters.",
equalTo: "Your password does not match."
}
}
});
});
</script>
自定义验证方法
<form id="myform">
<label for="username">Username:</label>
<input class="left" id="username" name="username" />
<br/>
<label for="email">Email:</label>
<input class="left" id="email" name="email" />
<br/>
<input class="submit" type="submit" value="Submit"/>
</form>
<script>
// 添加自定义验证方法
$.validator.addMethod("username", function(value, element) {
return /^[a-zA-Z]\w+$/.test(value);
}, "Please enter a valid username.");
$(document).ready(function(){
$("#myform").validate({
rules: {
username: {
required: true,
username: true // 使用自定义验证方法
},
email: {
required: true,
email: true // 邮箱验证
}
},
messages: {
username: {
required: "Username is required."
},
email: {
required: "Email is required.",
email: "Please enter a valid email."
}
}
});
});
</script>
结语
本文简要介绍了 jQuery验证插件validation 的使用方法,包括基本使用和自定义验证方法。相信大家通过本文的介绍,可以更好地掌握该插件的使用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:jQuery验证插件validation使用指南 - Python技术站