关于jQuery表单校验

<style>
.red{border: 1px solid red;}
.wrong-tip{color: red;}
</style>

  

<form action="http://fanyi.baidu.com/">
昵称:<input type="text" class="name"> 密码:<input type="password" class="password"><br/><br/>
<div class="wrong-tip"></div>
<input type="submit" value="提交" class="submit" />
</form>

  

<script type="text/javascript" src="js/jquery.min.js"></script>
		<script>
			$(function() {
				var ok1 = false;
				var ok2 = false;

				function check1() {
					if($(".name").val().length >= 3 && $(".name").val().length <= 12 && $(".name").val() != '') {
						$(".name").removeClass("red");
						$(".wrong-tip").html("");
						ok1 = true;
					} else {
						$(".name").addClass("red");
						$(".wrong-tip").html("用户名应该为3-20位之间!");
						ok1 = false;
					}
				}

				function check2() {
					if($(".password").val().length >= 6 && $(".password").val().length <= 20 && $(".password").val() != '') {
						$(".password").removeClass("red");
						$(".wrong-tip").html("");
						ok2 = true;
					} else {
						$(".password").addClass("red");
						$(".wrong-tip").html("密码应该为6-20位之间!");
						ok2 = false;
					}
				}

				$(".name").blur(function() {
					check1();
				})
				$(".password").blur(function() {
					check2();
				})

				$(".submit").click(function() {
					check1();
					check2();
					if(ok1 && ok2) {
						return true;
						//如果用的是模拟按钮,则用这个。 $('form').submit();
					} else {
						return false;
					}
				})
			})
		</script>

 以前觉得表单校验好难,今天终于弄明白了。

原文地址:https://www.cnblogs.com/xuemingyao/p/6023669.html