两个form表单同时校验

需求

效果图
要求: 一个页面两个form,要求所有字段必填

代码

将表格上的rules改到点击确定按钮的时候去校验

<el-button type="primary" class="nb-primary-btn-style" round @click="validateEdit"
>确 定</el-button>

//提交编辑
validateEdit() {
	// 校验表单一
  let dispatchValidate = new Promise((resolve, reject) => {
    this.$refs.ruleForm.validate((valid) => {
      if (valid) {
        resolve();
      } else {
        return false;
      }
    });
  });
  let formValidate;
  if (this.titleName == 'add') {
    // 校验表单二
    formValidate = new Promise((resolve, reject) => {
    	this.$refs.contractForm.validate((valid) => {
      	if (valid) {
        	resolve();
        } else {
          return false;
        }
      });
    });
  }

  // Promise.all统一处理
  Promise.all([dispatchValidate, formValidate]).then(() => {
    // 后续表单提交操作
    this.submitEdit();
  });
},
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 `async-validator` 库来实现多个表单的同时校验。具体步骤如下: 1. 安装 `async-validator` 库 ```bash npm install async-validator --save ``` 2. 在需要使用的组件中引入 `async-validator` ```javascript import AsyncValidator from 'async-validator'; ``` 3. 创建验证规则 ```javascript const rules = { name: [ { required: true, message: '请输入姓名' }, { min: 2, max: 10, message: '姓名长度为2-10个字符' } ], age: [ { required: true, message: '请输入年龄' }, { type: 'number', message: '年龄必须为数字' }, { min: 1, max: 120, message: '请输入正确的年龄范围' } ], // 其他字段的验证规则 } ``` 4. 编写校验方法,在方法中使用 `async-validator` 进行校验 ```javascript validateForm(form) { return new Promise((resolve, reject) => { const validator = new AsyncValidator(rules); validator.validate(form, { firstFields: true }, (errors, fields) => { if (errors) { reject(errors); } else { resolve(); } }); }); }, ``` 5. 在需要校验表单的地方调用校验方法 ```javascript this.validateForm(this.form1) .then(() => { // 表单1校验成功 this.validateForm(this.form2) .then(() => { // 表单2校验成功 console.log('表单校验成功'); }) .catch(errors => { // 表单2校验失败 console.log(errors); }); }) .catch(errors => { // 表单1校验失败 console.log(errors); }); ``` 这样就可以实现多个表单的同时校验了。注意,需要在校验方法中使用 `Promise` 对象返回校验结果,以便在调用校验方法的地方进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值