JS 表单验证不使用alert框

来源:互联网 发布:混乱与秩序无网络连接 编辑:程序博客网 时间:2024/06/11 02:48

使用说明:
1、消息显示对象id = 输入表单id + _msg
如用户名输入表单id=txt_username,消息显示对象id=txt_username_msg

2、错误消息:写在输入表单的title里,具体如下


 

用户名:<input type="text" name="txt_username" id="txt_username" onblur="CheckInput(this, 'username')" title="用户名不能为空,应为4-20个字母数字组成!"/><span id="txt_username_msg"></span><br/>密码:<input type="text" name="txt_password" id="txt_password" onblur="CheckInput(this, 'password')" title="密码不能为空,应为6-20个非空字符组成!"/><span id="txt_password_msg"></span><script>//参数说明 ,o : 检查对象 ,sType : 数据类型function CheckInput(o ,sType){  var msg=document.getElementById(o.id + '_msg');  //用户名  if(sType=='username'){ msg.innerHTML=(!/^[a-z0-9]{4,20}$/gi.test(o.value))? o.title : '√';  }  //密码  if(sType=='password'){ msg.innerHTML=(!/^[\S]{6,20}$/gi.test(o.value))? o.title : '√';  }  //更多数据类型验证方法可以自己添加....}</script>