在提交表单时,可以使用'v-if'指令或者'computed'属性来判断自定义验证规则是否通过。具体实现步骤如下:

1. 在表单元素上绑定自定义验证规则,例如:

<template>
  <form>
    <input type="text" v-model="name" :class="{'is-invalid': !isValidName}"/>
    <button @click.prevent="submitForm" :disabled="!isFormValid">Submit</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      name: '',
    }
  },
  computed: {
    isValidName() {
      // 自定义验证规则
      return this.name.length >= 3 && this.name.length <= 20;
    },
    isFormValid() {
      // 判断表单是否通过验证
      return this.isValidName;
    }
  },
  methods: {
    submitForm() {
      // 提交表单
    }
  }
}
</script>

2. 在表单提交按钮上绑定'disabled'属性,当表单不通过验证时禁用按钮,例如:

<button @click.prevent="submitForm" :disabled="!isFormValid">Submit</button>

3. 在表单提交方法中判断表单是否通过验证,例如:

methods: {
  submitForm() {
    if (this.isFormValid) {
      // 表单通过验证,可以进行提交操作
    } else {
      // 表单未通过验证,提示用户输入正确的信息
    }
  }
}
Vue 表单自定义验证规则:提交前判断内容

原文地址: https://www.cveoy.top/t/topic/ot0A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录