做過校驗需求的小伙伴們都知道,校驗其實是個麻煩事。
規則多,需要校驗的字段多,都給我們前端帶來巨大的工作量。
一個不小心,代碼里就出現了不少if else等不可維護的代碼。
因此,我覺得一個團隊或者是一個項目,需要一個校驗工具,簡化我們的工作。
首先,參考一下 Joi。只看這一小段代碼:
Joi.string().alphanum().min(3).max(30).required()
我希望我的校驗工具Coi也是鏈式調用,鏈式調用可以極大的簡化代碼。
校驗呢,其實主要就3個入參:需要校驗的數據,提示的錯誤信息,校驗規則。
哎 直接把代碼貼出來吧,反正就一百行,一目了然:
export default class Coi { constructor(prop) { this.input = prop this.errorMessage = '通過校驗' // 錯誤信息 this.pass = true // 校驗是否通過 } // 數據輸入 data(input) { if (!this.pass) return this this.input = input return this } // 必填,不能為空 isRequired(message) { if (!this.pass) return this if ( /^/s*$/g.test(this.input) || this.input === null || this.input === undefined ) { this.errorMessage = message this.pass = false } return this } // 最小長度 minLength(length, message) { if (!this.pass) return this if (this.input.length < length) { this.errorMessage = message this.pass = false } return this } // 最大長度 maxLength(length, message) { if (!this.pass) return this if (this.input.length > length) { this.errorMessage = message this.pass = false } return this } // 需要的格式 number: 數字, letter: 字母, chinese: 中文 requireFormat(formatArray, message) { if (!this.pass) return this let formatMap = { number: 0, letter: 0, chinese: 0 } Object.keys(formatMap).forEach(key => { if (formatArray.includes(key)) formatMap[key] = 1 }) let formatReg = new RegExp( `^[${formatMap.number ? '0-9' : ''}${ formatMap.letter ? 'a-zA-Z' : '' }${formatMap.chinese ? '/u4e00-/u9fa5' : ''}]*$` ) if (!formatReg.test(this.input)) { this.errorMessage = message this.pass = false } return this } // 郵箱校驗 isEmail(message) { if (!this.pass) return this const emailReg = /^[a-z0-9]+([._//-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/ if (!emailReg.test(this.input)) { this.errorMessage = message this.pass = false } return this } // ulr校驗 isURL(message) { if (!this.pass) return this const urlReg = new RegExp( '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?://S+(?:://S*)?@)?(?:(?:(?:[1-9]//d?|1//d//d|2[01]//d|22[0-3])(?://.(?:1?//d{1,2}|2[0-4]//d|25[0-5])){2}(?://.(?:[0-9]//d?|1//d//d|2[0-4]//d|25[0-4]))|(?:(?:[a-z//u00a1-//uffff0-9]+-?)*[a-z//u00a1-//uffff0-9]+)(?://.(?:[a-z//u00a1-//uffff0-9]+-?)*[a-z//u00a1-//uffff0-9]+)*(?://.(?:[a-z//u00a1-//uffff]{2,})))|localhost)(?:://d{2,5})?(?:(/|//?|#)[^//s]*)?$', 'i' ) if (!urlReg.test(this.input)) { this.errorMessage = message this.pass = false } return this } // 自定義正則校驗 requireRegexp(reg, message) { if (!this.pass) return this if (!reg.test(this.input)) { this.errorMessage = message this.pass = false } return this }}
新聞熱點
疑難解答
圖片精選