小程序表單驗(yàn)證 WxValidate 引入及基本使用
創(chuàng)建目錄:utils/WxValidate .js
/**
* 表單驗(yàn)證
*
* @param {Object} rules 驗(yàn)證字段的規(guī)則
* @param {Object} messages 驗(yàn)證字段的提示信息
*
*/
class WxValidate {
constructor(rules = {}, messages = {}) {
Object.assign(this, {
data: {},
rules,
messages,
})
this.__init()
}
/**
* __init
*/
__init() {
this.__initMethods()
this.__initDefaults()
this.__initData()
}
/**
* 初始化數(shù)據(jù)
*/
__initData() {
this.form = {}
this.errorList = []
}
/**
* 初始化默認(rèn)提示信息
*/
__initDefaults() {
this.defaults = {
messages: {
required: '這是必填字段。',
email: '請(qǐng)輸入有效的電子郵件地址。',
tel: '請(qǐng)輸入11位的手機(jī)號(hào)碼。',
url: '請(qǐng)輸入有效的網(wǎng)址。',
date: '請(qǐng)輸入有效的日期。',
dateISO: '請(qǐng)輸入有效的日期(ISO),例如:2009-06-23,1998/01/22。',
number: '請(qǐng)輸入有效的數(shù)字。',
digits: '只能輸入數(shù)字。',
idcard: '請(qǐng)輸入18位的有效身份證。',
equalTo: this.formatTpl('輸入值必須和 {0} 相同。'),
contains: this.formatTpl('輸入值必須包含 {0}。'),
minlength: this.formatTpl('最少要輸入 {0} 個(gè)字符。'),
maxlength: this.formatTpl('最多可以輸入 {0} 個(gè)字符。'),
rangelength: this.formatTpl('請(qǐng)輸入長(zhǎng)度在 {0} 到 {1} 之間的字符。'),
min: this.formatTpl('請(qǐng)輸入不小于 {0} 的數(shù)值。'),
max: this.formatTpl('請(qǐng)輸入不大于 {0} 的數(shù)值。'),
range: this.formatTpl('請(qǐng)輸入范圍在 {0} 到 {1} 之間的數(shù)值。'),
}
}
}
/**
* 初始化默認(rèn)驗(yàn)證方法
*/
__initMethods() {
const that = this
that.methods = {
/**
* 驗(yàn)證必填元素
*/
required(value, param) {
if (!that.depend(param)) {
return 'dependency-mismatch'
} else if (typeof value === 'number') {
value = value.toString()
} else if (typeof value === 'boolean') {
return !0
}
return value.length > 0
},
/**
* 驗(yàn)證電子郵箱格式
*/
email(value) {
return that.optional(value) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value)
},
/**
*
* 驗(yàn)證車牌號(hào)
*/
car_no(value) {
return that.optional(value) || /^[A-Z_0-9]{5,6}$/.test(value)
},
/**
* 驗(yàn)證手機(jī)格式
*/
tel(value) {
return that.optional(value) || /^1[34578]\d{9}$/.test(value)
},
/**
* 驗(yàn)證URL格式
*/
url(value) {
return that.optional(value) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-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,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value)
},
/**
* 驗(yàn)證日期格式
*/
date(value) {
return that.optional(value) || !/Invalid|NaN/.test(new Date(value).toString())
},
/**
* 驗(yàn)證ISO類型的日期格式
*/
dateISO(value) {
return that.optional(value) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
},
/**
* 驗(yàn)證十進(jìn)制數(shù)字
*/
number(value) {
return that.optional(value) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)
},
/**
* 驗(yàn)證整數(shù)
*/
digits(value) {
return that.optional(value) || /^\d+$/.test(value)
},
/**
* 驗(yàn)證身份證號(hào)碼
*/
idcard(value) {
return that.optional(value) || /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)
},
/**
* 驗(yàn)證兩個(gè)輸入框的內(nèi)容是否相同
*/
equalTo(value, param) {
return that.optional(value) || value === that.data[param]
},
/**
* 驗(yàn)證是否包含某個(gè)值
*/
contains(value, param) {
return that.optional(value) || value.indexOf(param) >= 0
},
/**
* 驗(yàn)證最小長(zhǎng)度
*/
minlength(value, param) {
return that.optional(value) || value.length >= param
},
/**
* 驗(yàn)證最大長(zhǎng)度
*/
maxlength(value, param) {
return that.optional(value) || value.length <= param
},
/**
* 驗(yàn)證一個(gè)長(zhǎng)度范圍[min, max]
*/
rangelength(value, param) {
return that.optional(value) || (value.length >= param[0] && value.length <= param[1])
},
/**
* 驗(yàn)證最小值
*/
min(value, param) {
return that.optional(value) || value >= param
},
/**
* 驗(yàn)證最大值
*/
max(value, param) {
return that.optional(value) || value <= param
},
/**
* 驗(yàn)證一個(gè)值范圍[min, max]
*/
range(value, param) {
return that.optional(value) || (value >= param[0] && value <= param[1])
},
}
}
/**
* 添加自定義驗(yàn)證方法
* @param {String} name 方法名
* @param {Function} method 函數(shù)體,接收兩個(gè)參數(shù)(value, param),value表示元素的值,param表示參數(shù)
* @param {String} message 提示信息
*/
addMethod(name, method, message) {
this.methods[name] = method
this.defaults.messages[name] = message !== undefined ? message : this.defaults.messages[name]
}
/**
* 判斷驗(yàn)證方法是否存在
*/
isValidMethod(value) {
let methods = []
for (let method in this.methods) {
if (method && typeof this.methods[method] === 'function') {
methods.push(method)
}
}
return methods.indexOf(value) !== -1
}
/**
* 格式化提示信息模板
*/
formatTpl(source, params) {
const that = this
if (arguments.length === 1) {
return function() {
let args = Array.from(arguments)
args.unshift(source)
return that.formatTpl.apply(this, args)
}
}
if (params === undefined) {
return source
}
if (arguments.length > 2 && params.constructor !== Array) {
params = Array.from(arguments).slice(1)
}
if (params.constructor !== Array) {
params = [params]
}
params.forEach(function(n, i) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function() {
return n
})
})
return source
}
/**
* 判斷規(guī)則依賴是否存在
*/
depend(param) {
switch (typeof param) {
case 'boolean':
param = param
break
case 'string':
param = !!param.length
break
case 'function':
param = param()
default:
param = !0
}
return param
}
/**
* 判斷輸入值是否為空
*/
optional(value) {
return !this.methods.required(value) && 'dependency-mismatch'
}
/**
* 獲取自定義字段的提示信息
* @param {String} param 字段名
* @param {Object} rule 規(guī)則
*/
customMessage(param, rule) {
const params = this.messages[param]
const isObject = typeof params === 'object'
if (params && isObject) return params[rule.method]
}
/**
* 獲取某個(gè)指定字段的提示信息
* @param {String} param 字段名
* @param {Object} rule 規(guī)則
*/
defaultMessage(param, rule) {
let message = this.customMessage(param, rule) || this.defaults.messages[rule.method]
let type = typeof message
if (type === 'undefined') {
message = `Warning: No message defined for ${rule.method}.`
} else if (type === 'function') {
message = message.call(this, rule.parameters)
}
return message
}
/**
* 緩存錯(cuò)誤信息
* @param {String} param 字段名
* @param {Object} rule 規(guī)則
* @param {String} value 元素的值
*/
formatTplAndAdd(param, rule, value) {
let msg = this.defaultMessage(param, rule)
this.errorList.push({
param: param,
msg: msg,
value: value,
})
}
/**
* 驗(yàn)證某個(gè)指定字段的規(guī)則
* @param {String} param 字段名
* @param {Object} rules 規(guī)則
* @param {Object} data 需要驗(yàn)證的數(shù)據(jù)對(duì)象
*/
checkParam(param, rules, data) {
// 緩存數(shù)據(jù)對(duì)象
this.data = data
// 緩存字段對(duì)應(yīng)的值
const value = data[param] !== null && data[param] !== undefined ? data[param] : ''
// 遍歷某個(gè)指定字段的所有規(guī)則,依次驗(yàn)證規(guī)則,否則緩存錯(cuò)誤信息
for (let method in rules) {
// 判斷驗(yàn)證方法是否存在
if (this.isValidMethod(method)) {
// 緩存規(guī)則的屬性及值
const rule = {
method: method,
parameters: rules[method]
}
// 調(diào)用驗(yàn)證方法
const result = this.methods[method](value, rule.parameters)
// 若result返回值為dependency-mismatch,則說明該字段的值為空或非必填字段
if (result === 'dependency-mismatch') {
continue
}
this.setValue(param, method, result, value)
// 判斷是否通過驗(yàn)證,否則緩存錯(cuò)誤信息,跳出循環(huán)
if (!result) {
this.formatTplAndAdd(param, rule, value)
break
}
}
}
}
/**
* 設(shè)置字段的默認(rèn)驗(yàn)證值
* @param {String} param 字段名
*/
setView(param) {
this.form[param] = {
$name: param,
$valid: true,
$invalid: false,
$error: {},
$success: {},
$viewValue: ``,
}
}
/**
* 設(shè)置字段的驗(yàn)證值
* @param {String} param 字段名
* @param {String} method 字段的方法
* @param {Boolean} result 是否通過驗(yàn)證
* @param {String} value 字段的值
*/
setValue(param, method, result, value) {
const params = this.form[param]
params.$valid = result
params.$invalid = !result
params.$error[method] = !result
params.$success[method] = result
params.$viewValue = value
}
/**
* 驗(yàn)證所有字段的規(guī)則,返回驗(yàn)證是否通過
* @param {Object} data 需要驗(yàn)證數(shù)據(jù)對(duì)象
*/
checkForm(data) {
this.__initData()
for (let param in this.rules) {
this.setView(param)
this.checkParam(param, this.rules[param], data)
}
return this.valid()
}
/**
* 返回驗(yàn)證是否通過
*/
valid() {
return this.size() === 0
}
/**
* 返回錯(cuò)誤信息的個(gè)數(shù)
*/
size() {
return this.errorList.length
}
/**
* 返回所有錯(cuò)誤信息
*/
validationErrors() {
return this.errorList
}
}
export default WxValidate
使用一:引入驗(yàn)證類
import WxValidate from '../../utils/WxValidate'
使用二:初始化函數(shù)(驗(yàn)證的表單參數(shù) + 驗(yàn)證規(guī)則 + 驗(yàn)證提示 + 自定義驗(yàn)證規(guī)則)
initValidate(){ //初始化 需要驗(yàn)證的表單參數(shù) + 驗(yàn)證規(guī)則 + 驗(yàn)證提示 + 自定義驗(yàn)證規(guī)則
let rules = {
shop:{//門店
required:true
},
name:{//姓名
required:true
},
phone:{//電話
required:true,
tel:11
},
car_no:{//車牌號(hào)
required:true,
car_no:true
},
dist:{//車牌號(hào)歸屬地
required:true
},
brand:{//品牌
required:true
},
series:{//車系
required:true
},
model:{//車型
required:true
},
vin: {
required: false,
vin: true
}
},
message = {
shop:{//門店
required:"請(qǐng)選擇門店"
},
name:{//姓名
required:"請(qǐng)?zhí)顚懶彰?
},
phone:{//電話
required:"請(qǐng)?zhí)顚懯謾C(jī)號(hào)碼",
tel:"請(qǐng)輸入正確的手機(jī)號(hào)碼"
},
car_no:{//車牌號(hào)
required:"請(qǐng)輸入車牌號(hào)碼",
car_no:"車牌號(hào)碼有誤請(qǐng)重新輸入"
},
dist:{//車牌號(hào)歸屬地
required:"請(qǐng)選擇車牌號(hào)碼歸屬地"
},
brand:{//品牌
required:"請(qǐng)選擇品牌"
},
series:{//車系
required:"請(qǐng)選擇車系"
},
model:{//車型
required:"請(qǐng)選擇車型"
},
vin:{//車型
required:"請(qǐng)輸入正確vin碼",
vin: "vin碼輸入有誤請(qǐng)重輸輸入"
},
}
//WxValidate.addMethod 為自定義驗(yàn)證規(guī)則的方法,以下為示例,更多說情請(qǐng)搜索請(qǐng)?jiān)谠a上搜索addMethod
this.WxValidate = new WxValidate(rules, message)
this.WxValidate.addMethod('vin',(value, param)=> { //自定義驗(yàn)證規(guī)則
let patt = new RegExp(/^[a-z_A-Z_0-9]{17}$/)
return value == '' ? true : patt.test(value)
}, 'vin碼輸入有誤請(qǐng)重新輸入')
}
使用三: 掛載初始化函數(shù)
onLoad() {
this.initValidate()
}
使用四: 提交驗(yàn)證
async handlePay(){//支付
const that = this
const prams = {
shop: this.data.shop.name=="請(qǐng)選擇門店"?"":true,
name: this.data.customerName,
phone: this.data.customerPhone,
car_no: this.data.customerPlatenum2,
dist: this.data.data.customer.platenum1,
brand: this.data.brandInfo.brand=="請(qǐng)選擇品牌"?"":true,
series: this.data.brandInfo.series=="請(qǐng)選擇車系"?"":true,
model: this.data.brandInfo.model=="請(qǐng)選擇車型"?"":true,
vin: this.data.brandInfo.vin,
}
if(!this.WxValidate.checkForm(prams)){//觸發(fā)支付驗(yàn)證
const error = this.WxValidate.errorList[0]
wx.showModal({
title: '錯(cuò)誤',
content: error.msg
})
}else{
//發(fā)起支付
},