如何使用jQuery验证表单?
首先,您必须制作一个类似html的表单。
<html> <body> <h2>Validation of a form</h2> <form id="form" method="post" action=""> First name:<br> <input type="text" name="firstname" value="john"> <br> Last name:<br> <input type="text" name="lastname" value="Doe"> <br> Email:<br> <input type="email" name="u_email" value="johndoe@gmail.com"> <br> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
现在使用jQuery验证插件以更简单的方式验证表单的数据。
首先,在文件中添加jQuery库。
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
then add javascript code:
$(document).ready(function() {
$("#form").validate();
});
</script>然后使用简单语法定义规则。
jQuery(document).ready(function() {
jQuery("#forms).validate({
rules: {
firstname: 'required',
lastname: 'required',
u_email: {
required: true,
email: true,//add an email rule that will ensure the value entered is valid email id.
maxlength: 255,
},
}
});
});定义错误消息。
messages: {
firstname: 'This field is required',
lastname: 'This field is required',
u_email: 'Enter a valid email',
},现在终于提交表格了。
submitHandler: function(form) {
form.submit();
}热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短