JQuery验证input

2014-04-23 来源: 郭晨 发布在  http://www.cnblogs.com/soccer/p/3682513.html

jsp中表单如下:

<form method="post" action="AddPlayer">
<div class = "one">
名称:<input type="text" name="name" id="txtName">
</div>
<div class = "one">
身高:<input type="text" name="height" id="txtHeight" >
</div>
<div class = "one">
体重:<input type="text" name="weight" id="txtWeight" >
</div>
<div class = "one">
球队:<select name="teamId">
<c:forEach items="${ teamList }" var="team">
<option value="${ team.id }">${ team.name }</option>
</c:forEach>
</select>
</div>
<br>
<input type="submit" id = "insert" value="添加球员" >
<input type="reset" value="重置">
</form>

validate.jsp如下:

$(function(){
var flag = 0;
$("#insert").click(function() {
if(flag != 3){
alert("输入错误!!!");
return false;
}
});

$("form :input").blur(function(){
$(this).parent().find(".a2").remove();
if ($(this).is("#txtName")){
if(this.value==""){
var s1 = $("<span class='a2 error'>不能为空!</span>");
$(this).parent().append(s1);
}
else{
var s1 = $("<span class='a2 righta'>正确</span>");
$(this).parent().append(s1);
flag = flag + 1;
}
}
//end

if ($(this).is("#txtHeight,#txtWeight")){
if(this.value==""){
var s1 = $("<span class='a2 error'>不能为空!</span>");
$(this).parent().append(s1);
}
else if (this.value!=""&&!/^[0-9]*$/.test(this.value) ){
var s1 = $("<span class='a2 error'>请输入数字!</span>");
$(this).parent().append(s1);
}
else{
var s1 = $("<span class='a2 righta'>正确</span>");
$(this).parent().append(s1);
flag = flag + 1;
}
}
//end
});
});

validate.css略

这样就可以实验每个input的验证了!

相关文章