前言
我們?cè)僭谛〕绦蚪?jīng)常使用表單驗(yàn)證功能,但是如果重復(fù)書(shū)寫(xiě)相同的驗(yàn)證代碼會(huì)很麻煩,所以我們可以封裝一個(gè)驗(yàn)證類(lèi)。
validate.js
const numberReg = /^-?[1-9][0-9]?.?[0-9]*$/ //數(shù)字正則
const phoneReg = /^1[0-9]{10,10}$/ //手機(jī)號(hào)正則
// 策略對(duì)象
let strategys = new Map([
//判斷是否為空
['isEmpty', (value, errorMsg) => {
if (value === '') {
return errorMsg;
}
}],
// 限制最小長(zhǎng)度
['minLength', (value, length, errorMsg) => {
if (value.length < length) {
return errorMsg;
}
}],
// 限制最大長(zhǎng)度
['maxLength', (value, length, errorMsg) => {
if (value.length > length) {
return errorMsg;
}
}],
// 手機(jī)號(hào)碼格式
['phone', (value, errorMsg) => {
if (!phoneReg.test(value)) {
return errorMsg;
}
}],
//判斷數(shù)字
['number', (value, errorMsg) => {
if (!numberReg.test(value)) {
return errorMsg;
}
}]
])
class Validator {
constructor() {
this.cache = []; //保存校驗(yàn)規(guī)則
}
addRule(data, rules) {
var self = this;
for (let rule of rules) {
if (!rule || !rule.name || !rule.strategy) {
continue
}
let strategyAry = rule.strategy.split(":");
self.cache.push(function () {
let strategy = strategyAry.shift();
let errmsg = rule.errmsg;
strategyAry.unshift(data[rule.name]);
strategyAry.push(errmsg);
return strategys.get(strategy).apply(data, strategyAry);
});
}
}
check() {
let res = {
isOk: true,
errmsg: ''
}
for (let i = 0, fn; fn = this.cache[i++];) {
let msg = fn(); // 開(kāi)始效驗(yàn) 并取得效驗(yàn)后的返回信息
if (msg) {
res = {
isOk: false,
errmsg: msg
};
break;
}
}
return res
}
}
/**
* 工廠模式,便于后期維護(hù)
*/
function getValidator() {
let validator = new Validator()
return validator
}
export default getValidator
app.js
import getValidator from './utils/validate';
App({
getValidator: getValidator
})
const app = getApp()
Page({
onShow() {
let validator = app.getValidator()
let data = {
username: '323232223'
}
validator.addRule(data, [{
name: 'username',
strategy: 'isEmpty',
errmsg: '用戶(hù)名不能為空'
},
{
name: 'username',
strategy: 'minLength:6',
errmsg: '用戶(hù)名長(zhǎng)度不能小于6位'
},
{
name: 'username',
strategy: 'maxLength:8',
errmsg: '用戶(hù)名長(zhǎng)度不能大于8位'
}
]);
console.log(validator.check());
}
})