JS 简单的表单验证功能

HTML代码 

  <div><label for="name">姓名:</label><input type="text" id="name"></div>
  <div><label for="age">年龄:</label><input type="number" id="age"></div>
  <div><label for="phone">手机号:</label><input type="text" id="phone"></div>
  <div><label for="class">班级:</label><input type="text" id="class"></div>
  <div><label for="address">住址:</label><input type="text" id="address"></div>
  <button onclick="checking()">开始验证</button>

JS代码

let rules=[
      {field:'name',type:"string",require:true,length:10,message:"请输入姓名且最多输入10个字符"},
      {field:'age',type:"number",require:true,min:10,max:20,message:"请输入年龄且在10-20之间"},
      {field:'phone',type:"number",require:true,min:13000000000,max:19999999999,message:"请输入正确的手机号"},
      {field:'class',type:"string",require:true,length:50,message:"请输入班级且最多输入50个字符"},
      {field:'address',type:"string",require:false,length:50,message:"请输入住址且最多输入50个字符"},
    ]
    function checking(){
      let formobj={
        name:document.getElementById('name').value,
        age:document.getElementById('age').value,
        phone:document.getElementById('phone').value,
        class:document.getElementById('class').value,
        address:document.getElementById('address').value
      }
      let result = checkFun(formobj,rules)   //返回结果 判断是否验证成功
      console.log(result)
    }
    function checkFun(input,rules){
      for(let i in input){
        let item = rules.find(item=>item.field==i)
        if(item.require && !input[i]){
          console.error(item.message,'验证必输')
          return false
        }
        if(item.type=="string"){
          if(input[i].length>item.length){
            console.error(item.message,'长度不对')
            return false
          }
        }else if(item.type=="number"){
          if(item.require && +input[i]<item.min || +input[i]>item.max){
            console.error(item.message,"number大小不对")
            return false
          }
        }
      }
      return true
    }

  

posted @ 2022-06-13 16:42  伴月阁  阅读(125)  评论(0编辑  收藏  举报