为了账号安全,请及时绑定邮箱和手机立即绑定

利用jQuery实现表单验证功能

标签:
JQuery

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
font-family: 微软雅黑;
}
form span{
color: #f00;
font-weight: bold;
display: none;
}
</style>
<script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="jquery-1.8.3.js"></script>
</head>
<body>
<form>
<p>用户名:</p>
<p>
<input type="text" name="userName" class="auth">
<span>用户名不能为空</span>
</p>
<p>密码:</p>
<p>
<input type="text" name="pwd" class="auth">
<span>长度必须为6位</span>
</p>
<p>确认密码:</p>
<p>
<input type="text" name="rePwd" class="auth">
<span>两次密码必须为一致</span>
</p>
<p>
<button>提交</button>
</p>
</form>
</body>
<script type="text/javascript">

// 用户名验证
$('input[name=userName]').blur(function(){
val=$(this).val();   // 获取用户名
if(val.length==0){
//a=0;
$(this).data({'num':0});   // 绑定属性
$(this).next().show();  // 显示提示消息
}else{
//a=1;
$(this).data({'num':1});
$(this).next().hide();  // 隐藏掉提示信息
}
});
// 密码验证
$('input[name=pwd]').blur(function(){

val=this.value;   // 获取密码if(val.length<6){    //b=0;    $(this).data({'num':0});   // 绑定属性    $(this).next().show();    // 显示提示信息}else{    //b=1;    $(this).data({'num':1});   // 绑定属性    $(this).next().hide();   // 隐藏掉提示信息}

});

// 确认密码验证
$('input[name=rePwd]').blur(function(){
pwd=$('input[name=pwd]').val();    // 获取密码
repwd=$(this).val();    // 获取确认密码
if(pwd!=repwd){
//c=0;
$(this).data({'num':0});   // 绑定属性
$(this).next().show();   // 显示提示消息
}else{
//c=1;
$(this).data({'num':1});   // 绑定属性
$(this).next().hide();   // 隐藏掉提示信息
}
});

// 表单提交
$('form').submit(function(){
// 让3个文本框失去焦点
$('input.auth').blur();  // 失去焦点的方法
// r=a+b+c;
// if(r==3){
//  return true;  // 提交表单
// }else{
//  return false;   // 阻止表单提交
// }
//
// 第二种方式
r=0;
$('input.auth').each(function(){        
r+=$(this).data('num');   // 收集数据      
});
if(r==3)
return true;   // 提交表单
else
return false;  // 不提交表单
});
</script>
</html>

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
64
获赞与收藏
367

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消