vue 公用的一些驗證方法和使用,值得收藏!
在項目的根目錄下新建一個‘utils’文件夾 ,utils下新建validate.js
validate.js 代碼如下
export const checkVaild = (str, type) => { switch (type) { case 'phone': // 手機號 return /^1[0-9][0-9]{9}$/.test(str) case 'tel': // 座機 return /^(0\d{2,3}-\d{7,8}(-\d{1,4})?$)/.test(str) case 'card': // 身份證 return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str) case 'pwd': // 密碼以字母開頭,長度在6~20之間,包含大、小字母、數字 return /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,20}$/.test(str) // return /^(?![0-9]+$)(?![A-Z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(str) case 'postal': // 郵政編碼 return /[1-9]\d{5}(?!\d)/.test(str) case 'QQ': // QQ號 return /^[1-9][0-9]{4,9}$/.test(str) case 'email': // 郵箱 return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str) case 'money': // 金額(小數點2位) return /^\d*(?:\.\d{0,2})?$/.test(str) case 'URL': // 網址 return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str) case 'IP': // IP return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str) case 'date': // 日期時間 return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str) case 'number': // 數字 return /^[0-9]$/.test(str) case 'positiveInteger': // 正整數 return /^[1-9]\d*$/.test(str) case 'price': // 價格 return /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(str) // 價格非0則去掉'?' case 'english': // 英文 return /^[a-zA-Z]+$/.test(str) case 'chinese': // 中文 return /^[\u4E00-\u9FA5]+$/.test(str) case 'lower': // 小寫 return /^[a-z]+$/.test(str) case 'upper': // 大寫 return /^[A-Z]+$/.test(str) case 'HTML': // HTML標記 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str) default: return true } }
其他頁面按需引用 ,舉例使用以上封裝的驗證方法(驗證是否為正確的手機號碼)
import { checkVaild } from '../../utils/validate.js';
let myPhone =‘111’;
if (!checkVaild(myPone, 'phone')) {
alert('手機號碼格式不正確');
return false;
}

浙公網安備 33010602011771號