表单常见的正则匹配验证(身份证、电话号码、ip地址、金额输入等)

103 阅读1分钟

验证正则

  1. 电话:/^1(3|4|5|6|7|8|9)\d{9}$/
  2. 邮箱:/^([A-Za-z0-9_-])+@([A-Za-z0-9_-])+(.[A-Za-z0-9_-])+/
  3. 传真:/^(\d{3,4}-)?\d{7,8}$/
  4. 中文名:/^[\u4e00-\u9fa5]{0,}$/
  5. 性别:/^男|^女/
  6. 只能是数字和字母:/^[A-Za-z0-9]+$/
  7. 只能是数字:/^[0-9]+$/
  8. 金额(记得要先去掉千分符的逗号,可用replace方法):/^(([1-9]\d*)|\d)(.\d{1,2})?$/

金额处理

  1. 金额格式化,保留两位小数,超过两位直接截取,不做四舍五入
export function formatAmt(val) {
  if(val || Number(val) === 0) {
    const str = (val*1).toFixed(2)
    const intSum = str.substring(0, str.indexOf('.')).replace(/\B(?=(?:\d{3})+$)/g, ',')
    const dot = str.substring(str.length, str.indexOf('.')) // 取得小数部分
    const ret = intSum + dot
    return ret
  } else {
    return val
  }
}

2.去除千分符

export function deleteThounthen(num) {
  if(num && num !== undefined && num !== null || num === 0) {
    let _num = num
    _num = _num.toString()
    _num = _num.replace(/,/gi, '')
    return _num
  } else {
    return num
  }
}

3.金额转大写

transform() {
  let reg = /^[1-9]\d{0,12}(\.\d{1,2})?$/
  if (reg.test(value.replace(/,/g,''))) { return}
  let cnMoney = “零元整” 
  let stroutput = ""
  let strUnit =“仟佰拾亿仟佰拾万仟佰拾元角分”
  money += "00"
  let intPos = money.index0f('.')
  if (intPos >= θ) {
    money = money.substring(0, intpos)+ money.substr(intPos + 1,2) 
  }
  strUnit = strUnit.substr(strUnit.length - money.length) 
  for (let i = 0; i < money.length; i++) {
    stroutput +=“零壹贰叁肆伍陆柒捌玖”.substr(money .substr(i, 1), 1) + strUnit. substr(i,1)
  }
  cnMoney = str0utput.replace(/零角零分$/, "整").replace(/零[仟佰拾]/g,'零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, '零元')
  return cnMoney
}