vue正则校验,适合校验框多,可以定位是哪个输入框报错

#效果展示:

在这里插入图片描述
光标自动移动到报错位置,操作简单实用。

用法:

一个输入框时:
// 先引入Regular文件
import Regular from '../js/Regular.js'
 var VerifyArr = [
                    'required',
                    "需要验证的值",
                    this.$refs.licenseNo.name,
                    "提示语",
                    "验证的类型" // 如email mobile 等
                ]
 var result = new Regular(...VerifyArr).verify();
  if(result !== undefined){
      this.$refs[result].focus()
      return false
  }
多个输入框时:
// HTML vant框架结构
<van-field
   v-model.trim="email"
     clearable
     label="邮箱"
     placeholder="请输入邮箱便于接受电子保单"
     ref="email"
     name='email'
 />
 // HTML 普通input 
<input type="text"    v-model.trim="校验值" :required='required' ref="licenseNo" name="licenseNo" :label="提示语" >
import Regular from '../js/Regular.js'
// 校验代码
  var result =  new Regular().isVerify(this.$refs)
  if(result !== undefined){
       this.$refs[result].focus()
       return false
   }

#代码展示:

// 弹框目前依赖于vant框架 ,可以自行引入其他框架修改即可
/*
  说明: 正则校验
*/
import { Toast } from 'vant'
/**
 ** @method Regular
  * @param {Boolean||string})}[required]是否必传 可以为Boolean 也可以为字符串 当传“required”为真  必传Y
  * @param {any}[value]需要验证的值  必传Y
  * @param {String} [name] 你想要验证的类型 如:email 必传N 不传值时默认只需验证是否为null
  * @param {String} [tips] 有CustomReg时 必传Y
  * @param {String} [eleName]  ref 上的$el Y
  * @param {(/正则表达式/} [CustomReg]  非必传N 当CustomReg c传值时 name 不用传值
  * @return {string || undefined} 当校验不通过时会返回 dom 对应的name属性上的值;当校验通过时返回 undefined
 */
const isIdCardNo = function (num) {
  var idcard = num
  if (idcard == '') {
    return true
  }
  var regex1 = /^[1-9][0-7]\d{4}((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229))\d{3}(\d|X|x)?$/
  // 身份号码位数及格式检验
  switch (idcard.length) {
    case 15:
      if ((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0)) {
        var regex2 = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/// 测试出生日期的合法性
      } else {
        var regex2 = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/// 测试出生日期的合法性
      }

      if (regex2.test(idcard)) {
        return true
      } else {
        return false
      }
    case 18:
      if (regex1.test(idcard)) {
        var S = (parseInt(idcard[0]) + parseInt(idcard[10])) * 7 + (parseInt(idcard[1]) + parseInt(idcard[11])) * 9 + (parseInt(idcard[2]) + parseInt(idcard[12])) * 10 + (parseInt(idcard[3]) + parseInt(idcard[13])) * 5 + (parseInt(idcard[4]) + parseInt(idcard[14])) * 8 + (parseInt(idcard[5]) + parseInt(idcard[15])) * 4 + (parseInt(idcard[6]) + parseInt(idcard[16])) * 2 + parseInt(idcard[7]) * 1 + parseInt(idcard[8]) * 6 + parseInt(idcard[9]) * 3
        var Y = S % 11
        var M = 'F'
        var JYM = '10X98765432'
        M = JYM.substr(Y, 1)
        // 判断校验位
        if (M == idcard[17].toUpperCase()) {
          // alert(Errors[0]+"18");
          return true
        } else {
          // alert(Errors[3]);
          // showErrMsg = Errors[3];
          return false
        }
      } else {
        return false
      }
    default:
      // alert(Errors[1]);
      // showErrMsg = Errors[1];
      return false
  }
}
const empty = /^\s*$/g // 空白
const mobile = /1[\d*]{10}/ // 手机
const email = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/
const licenseNo = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4,5}[A-Z0-9挂学警港澳]{1}$/ // 车牌
const frameNo = /^[\dA-Z]{17}$/ // 车架号
// const licenseNoFrameNo = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$|^[\da-zA-Z]{6,17}$/
const engineNo = /^[\dA-Z*-/\s]{6,50}$/
const number = /^\d*(?:.\d*)?$/ // 数字校验
const identify = /^[\da-zA-Z]+$/
const zipCode = /^[1-9]\d{5}$/ // 邮政编码
const idCard = /^[1-9][\d*]{7}((0\d*)|(1[0-2*]))(([0|1|2|*]\d)|[3|*][0-1*])[\d*]{3}$|^[1-9][\d*]{5}[1-9*][\d*]{3}((0\d*)|([1*][0-2*]))(([0|1|2|*][\d*])|[3*][0-1*])[\d*]{3}([0-9]|X)$/ // 身份证
// const creditCode = /^[^_IOZSVa-z\W]{2}[\d*]{6}[^_IOZSVa-z\W*]{10}$/ // 统一社会信用代码
// const institutionCode = /^([0-9A-Z*]){8}-[0-9|X]$/ // 组织机构代码
const creditCode = /\S/ // 统一社会信用代码
const institutionCode = /\S/ // 组织机构代码
const any = /\S/ // 任何字符串
// const name = /^[a-z]{1,10}$/

class Regular {
  constructor (required, value, name, tips, eleName, CustomReg) { // 初始化
    [this.required, this.value, this.name, this.tips, this.eleName, this.CustomReg] = [required, value, name, tips, eleName, CustomReg]
  }

  verify () { // 校验函数
    if (this.value === undefined) {
      Toast(this.tips + '不能为空')
      return this.eleName
    }
    if (this.CustomReg === undefined) {
      // console.log(empty.test(this.value), this.value, this.eleName)
      if (empty.test(this.value) || this.value === null) { // 是否为空
        if (this.required || this.required === 'required') { // 是否必传
          Toast(this.tips + '不能为空')

          return this.eleName
        }
      } else {
        if (this.name !== undefined) {
          if (this.name === 'licenseNo') {
            if (!licenseNo.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'frameNo') {
            if (!frameNo.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'engineNo') {
            if (!engineNo.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'identify') {
            if (!identify.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'number') {
            if (!number.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'zipCode') {
            if (!zipCode.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'email') {
            if (!email.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'mobile') {
            if (!mobile.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'idCard') {
            
            if (!isIdCardNo(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
            // if (!idCard.test(this.value)) {
            //   Toast(this.tips + '格式错误')
            //   return this.eleName
            // }
          } else if (this.name === 'licenseNoFrameNo') {
            if (!(licenseNo.test(this.value) || frameNo.test(this.value) || engineNo.test(this.value))) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'creditCode') {
            if (!creditCode.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'institutionCode') {
            if (!institutionCode.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          } else if (this.name === 'any') {
            if (!any.test(this.value)) {
              Toast(this.tips + '格式错误')
              return this.eleName
            }
          }
          // else {
          //   Toast('对不起找不到 ' + this.name + ' 格式类型')
          //   return this.eleName
          // }
        }
      }
    } else {
      if (this.tips === undefined) {
        Toast('自定义正则请传提示语')
        return this.eleName
      }
      if (empty.test(this.value) || this.value === null) { // 是否为空
        if (this.required || this.required === 'required') {
          Toast(this.tips + '不能为空')
          return this.eleName
        }
      } else if (this.CustomReg.test(this.value)) {
        Toast(this.tips + '格式错误')
        return this.eleName
      }
    }
  }

  // 是否通过
  isVerify (refsObj) { // regVerArr每一条数据 都可以通过refsObj取值到 否则不可以使用这个方法  返回 this.name 或 undefined
    var regVerArr = []
    for (const item in refsObj) {
      // console.log(item,"itemitemitemitemitemitem")
      if (refsObj[item] !== undefined) {
        try {
          regVerArr.push([
            refsObj[item].required,
            refsObj[item].value,
            refsObj[item].$attrs.name,
            refsObj[item].label,
            item
          ])
        } catch (error) {
          for (let index = 0; index < refsObj[item].length; index++) {
            // console.log(refsObj[item][index].name,"refsObj[item][index].value")
            regVerArr.push([
              refsObj[item][index].required,
              refsObj[item][index].value,
              refsObj[item][index].name,
              refsObj[item][index].label,
              item
            ])
          }
        }
      }
    }
    var verifyReturn
    // console.log(regVerArr, 'regVerArr')
    for (const iterator of regVerArr) {
      // console.log(iterator, 'iteratoriterator')
      verifyReturn = new Regular(...iterator).verify()
      if (verifyReturn !== undefined) {
        // console.log('执行完了')
        return verifyReturn
      }
    }
  }
}
export default Regular

发布了16 篇原创文章 · 获赞 0 · 访问量 131

猜你喜欢

转载自blog.csdn.net/sank2017/article/details/104004598