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


 

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

 

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

復制代碼
export const regular = {
  // 驗證自然數
  naturalNumber: /^(([0-9]*[1-9][0-9]*)|(0+))$/,
  naturalNumberMsg: '請輸入自然數',
  // 英文
  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位以內的字符'
}
/**
 * @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'}
]
}
復制代碼

 

載自:https://www.cnblogs.com/ToBeBest/p/10174141.html 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM