DCloud 插件市场 有表单校验插件 , 也可以自己封装一个
需要 在 vue 页面 定义一个表单校验规则 rules
格式 :
// 表单校验规则
rules: {
// name 字段
userName: {
//正则 校验
rule: /\S/,
// 不为空 提示 name值
name: '用户名',
// 正则匹配成功 提示值
msg: '用户名不为空'
}
}
valdate.js
// 表单校验
export default (that, key, rules) => {
// 校验是否为空
if (that[key].trim().length === 0) {
// 弹框提示
uni.showToast({
title: that.rules[key].name + '不能为空',
icon: 'none'
});
return false;
}
// 校验 正则匹配
if (!that.rules[key].rule.test(that[key])) {
uni.showToast({
title: that.rules[key].msg,
icon: 'none'
});
return false;
}
return true;
}
form 拿到数据后 进行表单校验
formSubmit(e){
for (let key in e.detail.value) {
if (!this.$val(this,key,this.rules)) return
}
console.log('发送请求', JSON.stringify(e.detail.value)