vue中form 表單經常使用校驗封裝(async-validator)

新建一個js校驗文件validate.jsvue

export const regular = {
  // 驗證天然數
  naturalNumber: /^(([0-9]*[1-9][0-9]*)|(0+))$/,
  naturalNumberMsg: '請輸入天然數',
  // 微信號
  wechat: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/,
  wechatMsg: '請輸入正確的微信號碼',
  // 英文
  english: /^.[A-Za-z]+$/,
  englishMsg: '請輸入英文字符',
  // 座機
  telephone: /^\d{3}-\d{7,8}|\d{4}-\d{7,8}$/,
  telephoneMsg: '請輸入正確的座機號',
  // 銀行卡號碼
  bankCard: /^[1-9]\d{9,19}$/,
  bankCardMsg: '請輸入正確的銀行卡號碼',
  // 證件號碼
  IDNumber: /^[a-z0-9A-Z]{0,50}$/,
  IDNumberMsg: '請輸入正確的證件號碼',
  // 身份證號碼,包括15位和18位的
  IDCard: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{7}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
  IDCardMsg: '請輸入正確的身份證號碼',
  // QQ號碼
  qq: /^[1-9]\d{4,11}$/,
  qqMsg: '請輸入正確的QQ號碼',
  // 網址, 僅支持http和https開頭的
  url: /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?$/,
  urlMsg: '請輸入以http和https開頭的網址',
  // 0到20位的英文字符和數字
  enNum0to20: /^[a-z0-9A-Z]{0,20}$/,
  enNum0to20Msg: '請輸入20位之內的英文字符和數字',
  // 2到100位的中英文字符和空格
  cnEnSpace2to100: /^[a-zA-Z\u4E00-\u9FA5\s*]{2,100}$/,
  cnEnSpace2to100Msg: '請輸入2到100位的中英文字符和空格',
  // 數字和換行符
  numLinefeed: /^[0-9\n*]+$/,
  numLinefeedMsg: '請輸入數字和換行符',
  // 255位之內的字符
  char0to255: /^.{0,255}$/,
  char0to255Msg: '請輸入255位之內的字符',
  // 特殊字符
  specialChar: /^[^`~!@#$^&*()=|{}':;',/\\[\].<>?]*$/,
  specialCharMsg: '請刪除特殊字符',
  // 保留兩位小數
  twoDecimal: /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[0-9][0-9]*\.\d{1,2})))$/,
  twoDecimalMsg: '小數點保留最多兩位'  
}
/**
 * @description 排序值驗證,排序值不能夠大於255
 */
export const validateOrder = function (rule, value, callback) {
  if (parseInt(value) > 255) {
    return callback(new Error('排序值不能夠大於255'))
  } else {
    callback()
  }
}

使用的時候在vue文件中引入該js及須要用的函數微信

import {regular, validateOrder} from '@/libs/validate'
rules: {
  name: [
    {pattern: regular.cnEnSpace2to100, message: regular.cnEnSpace2to100Msg, trigger: 'blur'}
  ],
  mobile: [
    {pattern: regular.mobile, message: '請輸入正確的手機號碼', trigger: 'blur'}
  ],
  telephone: [
    {pattern: regular.telephone, message: regular.telephoneMsg, trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '請輸入正確的郵箱', trigger: 'blur'}
  ],
  idcard: [
    {pattern: regular.IDNumber, message: '請輸入正確的證件號碼', trigger: 'blur'}
],
bankCard: [
{pattern: regular.bankCard, message:
'請輸入正確的銀行卡號碼', trigger: 'blur'}
],
order: [
{type:
'string', validator: validateOrder, trigger: 'blur'} ]}
相關文章
相關標籤/搜索