微信小程序表單驗證怎么弄?
微信小程序表單驗證怎么弄?微信小程序正式上線,相信很多人都已經開始使用了。簡單的表單驗證,也不算是驗證了,只是封裝了一下提示消息,免得自己去手動寫if else(大家都懂吧),用起來還行吧,自己動手豐衣足食。

插件地址:https://github.com/skyvow/m-mall/blob/master/helpers/WxValidate.js
代碼示例:
/×*
* 創建驗證字段的工廠函數
*
* @param {Object} rules 驗證字段的規則
* @param {Object} messages 驗證字段的提示信息
*
*/
class WxValidate {
constructor(rules = {}, messages = {}) {
Object.assign(this, {
rules,
messages,
})
this.__init()
}
/×*
* __init
*/
__init() {
this.__initMethods()
this.__initDefaults()
this.__initErrorList()
}
/×*
* 初始化錯誤信息
*/
__initErrorList() {
this.errorList = []
}
/×*
* 初始化默認提示信息
*/
__initDefaults() {
this.defaults = {
messages: {
required: '這是必填字段。',
email: '請輸入有效的電子郵件地址。',
tel: '請輸入11位的手機號碼。',
url: '請輸入有效的網址。',
date: '請輸入有效的日期。',
dateISO: '請輸入有效的日期(ISO),例如:2009-06-23,1998/01/22。',
number: '請輸入有效的數字。',
digits: '只能輸入數字。',
idcard: '請輸入18位的有效身份證。',
equalTo: this.formatTpl('輸入值必須和 {0} 相同。'),
contains: this.formatTpl('輸入值必須包含 {0}。'),
minlength: this.formatTpl('最少要輸入 {0} 個字符。'),
maxlength: this.formatTpl('最多可以輸入 {0} 個字符。'),
rangelength: this.formatTpl('請輸入長度在 {0} 到 {1} 之間的字符。'),
min: this.formatTpl('請輸入不小于 {0} 的數值。'),
max: this.formatTpl('請輸入不大于 {0} 的數值。'),
range: this.formatTpl('請輸入范圍在 {0} 到 {1} 之間的數值。'),
}
}
}
/×*
* 初始化默認驗證方法
*/
__initMethods() {
const that = this
that.methods = {
/×*
* 驗證必填元素
*/
required(value, param) {
if (!that.depend(param)) {
return 'dependency-mismatch'
}
return value.length > 0
},
/×*
* 驗證電子郵箱格式
*/
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)
},
/×*
* 驗證手機格式
*/
tel(value) {
return that.optional(value) || /^1[34578]d{9}$/.test(value)
},
/×*
* 驗證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]|2d|3[0-1])(?:.d{1,3}){2})(?:[1-9]d?|1dd|2[01]d|22[0-3])(?:.(?:1?d{1,2}|2[0-4]d|25[0-5])){2}(?:.(?:[1-9]d?|1dd|2[0-4]d|25[0-4]))|(?:(?:[a-zu00a1-uffff0-9]-*)*[a-zu00a1-uffff0-9]+)(?:.(?:[a-zu00a1-uffff0-9]-*)*[a-zu00a1-uffff0-9]+)*(?:.(?:[a-zu00a1-uffff]{2,})).?)(?::d{2,5})?(?:[/?#]S*)?$/i.test(value)
},
/×*
* 驗證日期格式
*/
date(value) {
return that.optional(value) || !/Invalid|NaN/.test(new Date(value).toString())
},
/×*
* 驗證ISO類型的日期格式
*/
dateISO(value) {
return that.optional(value) || /^d{4}[/-](0?[1-9]|1[012])[/-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
},
/×*
* 驗證十進制數字
*/
number(value) {
return that.optional(value) || /^(?:-?d+|-?d{1,3}(?:,d{3})+)?(?:.d+)?$/.test(value)
},
/×*
* 驗證整數
*/
digits(value) {
return that.optional(value) || /^d+$/.test(value)
},
/×*
* 驗證身份證號碼
*/
idcard(value) {
return that.optional(value) || /^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{3}([0-9]|X)$/.test(value)
},
/×*
* 驗證兩個輸入框的內容是否相同
*/
equalTo(value, param) {
return that.optional(value) || value === that.scope.detail.value[param]
},
/×*
* 驗證是否包含某個值
*/
contains(value, param) {
return that.optional(value) || value.indexOf(param) >= 0
},
/×*
* 驗證最小長度
*/
minlength(value, param) {
return that.optional(value) || value.length >= param
},
/×*
* 驗證比較大長度
*/
maxlength(value, param) {
return that.optional(value) || value.length <= param
},
/×*
* 驗證一個長度范圍[min, max]
*/
rangelength(value, param) {
return that.optional(value) || (value.length >= param[0] && value.length <= param[1])
},
/×*
* 驗證最小值
*/
min(value, param) {
return that.optional(value) || value >= param
},
/×*
* 驗證比較大值
*/
max(value, param) {
return that.optional(value) || value <= param
},
/×*
* 驗證一個值范圍[min, max]
*/
range(value, param) {
return that.optional(value) || (value >= param[0] && value <= param[1])
},
}
}
/×*
* 添加自定義驗證方法
* @param {String} name 方法名
* @param {Function} method 函數體,接收兩個參數(value, param),value表示元素的值,param表示參數
* @param {String} message 提示信息
*/
addMethod(name, method, message) {
this.methods[name] = method
this.defaults.messages[name] = message !== undefined ? message : this.defaults.messages[name]
}
/×*
* 判斷驗證方法是否存在
*/
isValidMethod(value) {
let methods = []
for(let method in this.methods) {
if (method && typeof this.methods[method] === &#39;function&#39;) {
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
}
/×*
* 判斷規則依賴是否存在
*/
depend(param) {
switch(typeof param) {
case &#39;boolean&#39;:
param = param
break
case &#39;string&#39;:
param = !!param.length
break
case &#39;function&#39;:
param = param()
default:
param = !0
}
return param
}
/×*
* 判斷輸入值是否為空
*/
optional(value) {
return !this.methods.required(value) && &#39;dependency-mismatch&#39;
}
/×*
* 獲取自定義字段的提示信息
* @param {String} param 字段名
* @param {Object} rule 規則
*/
customMessage(param, rule) {
const params = this.messages[param]
const isObject = typeof params === &#39;object&#39;
if (params && isObject) return params[rule.method]
}
/×*
* 獲取某個指定字段的提示信息
* @param {String} param 字段名
* @param {Object} rule 規則
*/
defaultMessage(param, rule) {
let message = this.customMessage(param, rule) || this.defaults.messages[rule.method]
let type = typeof message
if (type === &#39;undefined&#39;) {
message = `Warning: No message defined for ${rule.method}.`
} else if (type === &#39;function&#39;) {
message = message.call(this, rule.parameters)
}
return message
}
/×*
* 緩存錯誤信息
* @param {String} param 字段名
* @param {Object} rule 規則
* @param {String} value 元素的值
*/
formatTplAndAdd(param, rule, value) {
let msg = this.defaultMessage(param, rule)
this.errorList.push({
param: param,
msg: msg,
value: value,
})
}
/×*
* 驗證某個指定字段的規則
* @param {String} param 字段名
* @param {Object} rules 規則
* @param {Object} event 表單數據對象
*/
checkParam(param, rules, event) {
// 緩存表單數據對象
this.scope = event
// 緩存字段對應的值
const data = event.detail.value
const value = data[param] || &#39;&#39;
// 遍歷某個指定字段的所有規則,依次驗證規則,否則緩存錯誤信息
for(let method in rules) {
// 判斷驗證方法是否存在
if (this.isValidMethod(method)) {
// 緩存規則的屬性及值
const rule = {
method: method,
parameters: rules[method]
}
// 調用驗證方法
const result = this.methods[method](value, rule.parameters)
// 若result返回值為dependency-mismatch,則說明該字段的值為空或非必填字段
if (result === &#39;dependency-mismatch&#39;) {
continue
}
// 判斷是否通過驗證,否則緩存錯誤信息,跳出循環
if (!result) {
this.formatTplAndAdd(param, rule, value)
break
}
}
}
}
/×*
* 驗證所有字段的規則,返回驗證是否通過
* @param {Object} event 表單數據對象
*/
checkForm(event) {
this.errorList = []
for (let param in this.rules) {
this.checkParam(param, this.rules[param], event)
}
return this.valid()
}
/×*
* 返回驗證是否通過
*/
valid() {
return this.size() === 0
}
/×*
* 返回錯誤信息的個數
*/
size() {
return this.errorList.length
}
/×*
* 返回所有錯誤信息
*/
validationErrors() {
return this.errorList
}
}
export default WxValidate
下面小編就給大家介紹一個小程序吧
嗨圖功能

1、專題——DIY圖片的模板,點擊可以生成使用,分享到朋友圈。
2、分享墻——用戶上傳的自己DIY作品。
3、立即制作——可以用自己的圖來DIY。
4、告訴我——告訴產品的改進,內容的增加。
想要體驗怎么制作屬于自己個性朋友圈照片的用戶,掃一掃下面的二維碼就可以啦!還等什么,趕緊掃碼體驗,開啟你的嗨圖之旅吧!

相關文章: