1.开发环境 vue2+vee-validate2
2.电脑系统 windows11专业版
3.在开发的过程中,我们经常会使用到表单来处理数据,但是表单的数据怎么校验呢?下面我来分享一下方法,希望对你有所帮助。
4.安装:
npm install vee-validate --save
4-1.在main.js或者index.js中引入:
import veeCustomSet from 'veeCustomSetAdmin';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);
veeCustomSet.localizeDictionary(VeeValidate);
veeCustomSet.extendRegex(VeeValidate);
4-2.在对应的页面中使用:
// template代码
methods代码
extendValidate() {
this.$validator.extend('isCellPhone', {
getMessage() {
return `必填`;
},
validate(value, arg) {
if ((!!arg[1] && (arg[1] == value)) || value == '') {
return true;
}
return new Promise((resolve) => {
// _this.$Axios.post('',{
// phone: value
// }).then((res) => {
// let result = true;
// if (res.code != 1000000) {
// result = false;
// }
// return resolve({
// valid: result
// });
// });
return resolve({
valid: true
});
});
}
});
},
// 效果如下:
// 手机号输入不对
// 手机号为空
4-3.提交的时候,验证表单数据:
Submit() {
const _this = this;
console.log(this.showAuthentication);
switch (this.showAuthentication) {
case 1:
console.log("新增");
this.$refs.tipModal.confirm({
autoClose: false,
beforeOpen() {
console.log("00000");
_this.$nextTick(() => {
_this.errors.clear();
_this.$validator.validateAll().then((e) => {
if (e) {
console.log(e);
// _this.$Axios.post('',{
// phone: _this.formData.phone,
// name: _this.formData.name,
// type: _this.formData.type
// }).then(() => {
// _this.$refs.alertConfirm.close();
// _this.$refs.appTable.refresh();
// });
} else {
console.log("+++++++++");
console.log(e);
console.log("+++++++++");
}
});
});
}
});
break;
case 2:
console.log("修改");
break;
default:
this.$refs.tipModal.confirm({
autoClose: false,
beforeOpen() {
_this.$nextTick(() => {
_this.errors.clear();
});
},
confirm() {
_this.$validator.validateAll().then((e) => {
if (e) {
console.log(e);
// _this.$Axios.post('',{
// phone: _this.formData.phone,
// name: _this.formData.name,
// type: _this.formData.type
// }).then(() => {
// _this.$refs.alertConfirm.close();
// _this.$refs.appTable.refresh();
// });
}
});
}
});
}
}
// 效果如下:
// 没有填写,表单数据为空
// 验证不通过
注意::::根据_this.$validator.validateAll().then((e)的e(布尔值)
来判断是否调用接口,如果验证灭有通过就不调用接口,如果验证通过就调用接口
4-4.template全部代码:
4-5.引入modal
import modal from 'vueModal_v2';
// 注册
components: {
'modal': modal
},
5.本期的分享到了这里就结束啦,希望对你有所帮助,让我们一起努力走向巅峰。