html5 form表单验证

536 阅读1分钟
1.移动端 html5 input date 不支持 placeholder 问题
<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" />
或者用 div 模拟
2.html5表单新增了哪些类型
email url number range date search color tel
autocomplete  
list datalist  <input list="id">  <dataList><option value /></dataList>
autofocus
必填 required 
正则 pattern
不验证 novalidate | formnovalidate
3.去除自动填充黄色背景
autocomplete='off'
input:-webkit-autofill{
    -webkit-box-shadow:0 0 0px 1000px #2390cc inset
}
4.去除输入框 xinput[type='search']::webkit-search-cancel-button{ //手机端兼容性不好
      -webkit-appearance:none; 
  }
4.form enctype="multipart/form-data" | application/x-www-form-urlencoded
5. 约束验证 api
   willValidate
   vailidity // dom.validity
      {
          badInput
          customError // setCustomValidity()
          patternMismatch //pattern
          rangeOverflow //max
          stepMismatch 
          tooLong  // maxlength
          typeMismatch   //不符合类型
          valueMissing  // required
      }
   validationMessage //验证错误提示信息
   checkValidity()方法  //ipt.checkValidty() , 所有约束条件都验证通过了返回 true
   setCustomValidity() //设置自定义验证信息,默认验证失败 tooltip 弹窗提示
 6.css 伪类选择器
   :required 和 :optional //必填和可选
   :in-range 和 :out-of-range
   :valid 和:invalid //验证正确和验证不正确
   :read-only 和 :read-write //只读和写读
 7.事件
   oninput=this.setCustomvalidity('')
   oninvalid=this.setCustomvalidity('请输入正确信息')
   onchange=""
 8.组织默认气泡提示窗
   form.addEventListener('invalid',function(e){
     e.preventDefault()
   },true)
   form.addEventListener('submit',function(e){
     if(!checke()){
         e.preventDefult()
     }
   },true)
   form.addEventListener('click',function(e){
       //所有默认的错误提示信息,先进行移除所有,后插入
       errorMessage=form.querySelectotAll('.error-message') 
       invalidField=form.querySelectorAll(':invalid')
       for(var i=0;i<invalidField.length;i++){
           parent=invalidField[i].parentNode
           parent.insertAdjacentHTML('beforeend',`<div class="error-message">invalidFild[i].validationMessage</div>`)
       }  
   })
9.insertAdjacentHTML(where,html) //api
  where 取值:
    beforeBegin: 插入到标签开始标记前
    afterBegin:插入到标签开始标记之后
    beforeEnd:插入到标签结束标记前
    afterEnd:插入到标签结束标记后