html表单js验证

2022年9月19日10:33:33 发表评论
微信搜一搜 ts小陈

html表单js验证输入的信息是否正确

html表单js验证

  1. <script type="text/javascript">
  2.   //表单验证。from加id,表单加对应id
  3.          window.onload = function(){
  4.         document.getElementById("form").onsubmit = function(){
  5.                 return checkUsername() && checkMobilePhone(); //有几个验证就加几个
  6.         };
  7.             document.getElementById("username").onblur = checkUsername;
  8.             document.getElementById("telphone").onblur = checkMobilePhone;
  9.         }
  10.         function checkUsername(){
  11.             var username = document.getElementById("username").value;
  12.             var reg_username =/[\u4e00-\u9fa5]/;
  13.             var flag = reg_username.test(username);
  14.             var s_username = document.getElementById("s_username");
  15.             if(flag){
  16.                 return true; //正确继续往下执行
  17.             }else{
  18.               window.alert("请输入正确的姓名或称呼");//页面弹窗提醒信息(上边错误的也可以添加弹窗提醒)
  19.                 return false; //错误停止执行
  20.             }
  21.         }
  22.         function checkMobilePhone() {
  23.              //定义正则表达式的变量:1.手机号正则,/^[1][3,4,5,6,7,8,9][0-9]{9}$/ //2.电话号码正则:/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/
  24.         var telphone = document.getElementById("telphone").value;
  25.         var phoneReg= /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  26.         var flag = phoneReg.test(telphone);
  27.         var mobile_input = document.getElementById("mobile_input");
  28.          if(flag)
  29.         {
  30.               return true;
  31.         }else{
  32.             window.alert("请输入正确的手机号码");
  33.              return false;
  34.         }
  35.         }
  36.    function checkform(){
  37.             //表单总确认
  38.       if(checkUsername() && checkMobilePhone()==true){ //只有所有验证都通过才继续执行
  39.         return true;
  40.        }else{
  41.         window.alert("请您核对一下您的注册信息是否有误");
  42.         return false;
  43.        }
  44.    }
  45. </script>
  46. <form action="{pboot:msgaction}"  method="post" id="form">
  47.     联系人:<input type="text" name="contacts" id="username">
  48.     手机:<input type="text" name="mobile"  id="telphone" >
  49.     内容:<input type="text" name="content" >
  50.     <button type="submit" id="registerBtn" οnclick="checkform();">提交</button>
  51. </form>

以上代码验证了姓名和手机号,from添加id,需要验证的表单也要添加id

当然你也可以添加多个验证使用function checkUsername(),表单中添加对应id

小陈号卡
ts小陈

发表评论(不允许含有网址!)

:?: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :cry: :mrgreen: :neutral: :razz:

已登录用户不需要填写以下内容