您现在的位置是:网站首页> 编程资料编程资料
关于element-ui中el-form自定义验证(调用后端接口)_vue.js_
2023-05-24
364人已围观
简介 关于element-ui中el-form自定义验证(调用后端接口)_vue.js_
element-ui中el-form自定义验证
需求
在输入项目名称后,调用后端接口isNameOnly,若已存在,则效果如下图:

1.先设置校验规则rules
2.在return中定义
// 判定规则 rules: { taskName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }, { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }, { required: true, trigger: 'blur', //validatePass --- 我们自定义的校验规则 validator: validatePass } ], }, 3.在data中添加如下代码:(注意,以下代码和return同级)
const validatePass = (rule, value, callback) => { this.$depot.get({ url: '/isNameOnly', config: { params: { taskName: 1, userId: 1) } }, cb: (res) => { this.nameOK = res.data == 1 ? true : false } }) if (this.nameOK != false) { callback() } else { callback(new Error('经验证,该项目已存在于数据库中')) } } 4.method定义提交表单方法
// 提交表单数据 submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { this.$message({ message: '恭喜你!项目创建成功!', type: 'success' }); } else { this.$message({ message: '请按照提示正确输入信息后再创建!', center: true }); } }); }, element-ui自定义form表单校验规则
HTML:
注意
使用校验规则的表单,在data中定义的时候必须要放在一个对象中,:model="ruleForm"这行代码一定要写,不写不生效!
js:
export default { name: "", data() { //自定义校验规则 var checkIdCard = (rule, value, cb) => { const regIdCard = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; if (regIdCard.test(value)) { return cb(); } cb(new Error("您输入的身份证号码不是有效格式")); }; return { ruleForm: { id_card: "", //身份证 }, rules: { id_card: [ { required: true, message: "请输入身份证", trigger: "blur" }, { validator: checkIdCard, trigger: "blur" }, ], } }, element ui 官网也有详细介绍哦------https://element.eleme.cn/#/zh-CN/component/form
这样也就实现了自定义校验的规则,可以在项目中使用了!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- el-form-item prop属性动态绑定不生效问题及解决_vue.js_
- Vue中axios的基本用法详解_vue.js_
- Vue路由传参及props解耦深入分析_vue.js_
- JavaScript可视化与Echarts详细介绍_javascript技巧_
- vue-cli中设置publicPath的几种方式对比_vue.js_
- Vue出现弹出层时禁止底部页面跟随滑动_vue.js_
- 微信小程序使用webview打开pdf文档以及显示网页内容的方法步骤_javascript技巧_
- Vue3+TypeScript+Vite使用require动态引入图片等静态资源_vue.js_
- vue路由传参方式的方式总结及获取参数详解_vue.js_
- vue如何实现动态改变地址栏的参数值_vue.js_
