<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function(){ function checkinput_form1(_this){ alert(_this+" ------ " ); var _parent=$("#form1"); //var $this=$(this); var $this=_this; var _name=$this.attr("name"); var _val=$.trim($this.val()); var _console=$("#regError",_parent); switch(_name){ case "username": if (_val == "") { _console.addClass('red').text("请输入用户名");return false; } else if (!isName.test(_val)) { _console.addClass('red').text("用户名只能是手机或邮箱");return false; } else { _console.removeClass('red').html(" "); $.ajax({ type: "GET", url: "/reg/username", data: { "username": _val }, dataType: "jsonp", success: function(data) { if (data.status == 0) { _console.removeClass("red").html(" "); } else { _console.addClass("red").text(data.message); return false; } } }); } break; case "password": if (_val == "") { _console.addClass('red').text("请输入密码");return false; } else if (_val.indexOf(' ') != -1) { _console.addClass('red').text("密码中不能含有空格");return false; } else if (_val.length < 6 || _val.length > 20) { _console.addClass('red').text("密码长度为6-20位");return false; } else { _console.removeClass('red').html(" "); } break; case "repeatPassword": if (_val == "") { _console.addClass('red').text("请重复密码");return false; } else if (_val != _parent.find("input[name=password]").val()) { _console.addClass('red').text("密码不一致");return false; } else { _console.removeClass('red').html(" "); } break; } return true; } //遍历表单文本框 $("#form1 input[name]").each(function(){ $(this).bind( "blur", function(){checkinput_form1($(this)) });//注意blur事件写法! function checkinput_form1(_this) { } }) //表单提交 $("#form1").submit(function(){ var $this=$(this); $("input[name]",this).not("[type=hidden]").each(function(){ var _flag=checkinput_form1( $(this) );//表单验证 if(_flag==false) return false; }); }) }); </script> </head> <body> <form id="main-reg-form" method="post" action=""> <input type=text name="username"><br> <input type=text name="password"><br> <input type=text name="password2"><br> <input type="submit" value="提交"> </form> </body> </html>