antd vue form表单校验总结

三种校验方式

使用提交按钮

  • 案例常用,参考案例:表单的基本使用
      <a-button type="primary" html-type="submit">Submit</a-button>
    

使用formRef

  • 较为常用,参考案例:自定义校验规则
    <a-form ref="formRef" :model="modal.formQuery">
    
    import type { FormInstance } from 'ant-design-vue'
    
    const formRef = ref<FormInstance>()
    const testForm = () => {
      formRef.value
        ?.validate(['word'])  // 不加参数,会校验全部规则
        .then((res) => {
          console.log('通过', res)
        })
        .catch((err) => {
          console.log('失败', err)
        })
    }
    
    // 子组件初始化示例
    const init = () => {
      formRef.value?.resetFields()  // 初始化重置表单
    }
    defineExpose({ getLogisticsTemplateHandle }) // 导出该子组件方法
    
    // 父组件监听方法
    <Child ref="childInitRef" @init="childInit" />
    
    import { nextTick } from 'vue'
     
    type childTemplate = {
      init: () => void
    }
    const childInitRef = ref<childTemplate>() // 绑定子组件的ref
    const childInit = () => {
        nextTick(() => {
            if (childInitRef.value) childInitRef.value.init() // 直接调用子组件的init初始化方法
        })
    }
    

使用useForm

<template>
  <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
    // 使用 v-bind="validateInfos.type" 绑定需要校验的数据
    <a-form-item label="Activity name" v-bind="validateInfos.name">
      <a-input v-model:value="modelRef.name" />
    </a-form-item>
    <a-form-item label="Activity zone" v-bind="validateInfos.region">
      <a-select v-model:value="modelRef.region" placeholder="please select your zone">
        <a-select-option value="shanghai">Zone one</a-select-option>
        <a-select-option value="beijing">Zone two</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="Activity type" v-bind="validateInfos.type">
      <a-checkbox-group v-model:value="modelRef.type">
        <a-checkbox value="1" name="type">Online</a-checkbox>
        <a-checkbox value="2" name="type">Promotion</a-checkbox>
        <a-checkbox value="3" name="type">Offline</a-checkbox>
      </a-checkbox-group>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click.prevent="onSubmit">Create</a-button>
      <a-button style="margin-left: 10px" @click="resetFields">Reset</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts">
import { defineComponent, reactive, toRaw } from 'vue';
import { Form } from 'ant-design-vue';

const useForm = Form.useForm;
export default defineComponent({
  setup() {
    const modelRef = reactive({
      name: '',
      region: undefined,
      type: [],
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: 'Please input name',
        },
      ],
      region: [
        {
          required: true,
          message: 'Please select region',
        },
      ],
      type: [
        {
          required: true,
          message: 'Please select type',
          type: 'array',
        },
      ],
    });
    // 引入需要的方法,validateInfos绑定校验数据、validate规则验证、resetFields重置表单
    const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
      onValidate: (...args) => console.log(...args),
    });
    const onSubmit = () => {
      // 直接使用引入的`validate`进行校验
      validate()
        .then(() => {
          console.log(toRaw(modelRef));
        })
        .catch(err => {
          console.log('error', err);
        });
    };
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      validateInfos,
      resetFields,
      modelRef,
      onSubmit,
    };
  },
});
</script>

两种rules定义方式

定义在form-item

  • 通常搭配提交按钮校验通过校验失败等方法使用
    <a-form-item
      label="Username"
      name="username"
      :rules="[{ required: true, message: 'Please input your username!' }]"
    >
      <a-input v-model:value="formState.username" />
    </a-form-item>
    

定义在form

  • 使用频率较高,便于统一管理校验规则
    <a-form
    ref="formRef"
    name="custom-validation"
    :model="formState"
    :rules="rules"
    @finish="handleFinish"
    @validate="handleValidate"
    @finishFailed="handleFinishFailed"
    ></a-form>
    import type { Rule } from 'ant-design-vue/es/form'
    
    // 统一定义一个`rules`
    const rules: Record<string, Rule[]> = {
      pass: [{ required: true, validator: validatePass, trigger: 'change' }],
      checkPass: [{ validator: validatePass2, trigger: 'change' }],
      age: [{ validator: checkAge, trigger: 'change' }],
    }
    // 提取`validator`规则,独立定义`pass`
     const validatePass = async (_rule: Rule, value: string) => {
      if (value === '') {
        return Promise.reject('Please input the password'); // eslint会报错
        return Promise.reject(new Error('Please input the password')); // 加个new Error()
      } else {
        if (formState.checkPass !== '') {
          formRef.value.validateFields('checkPass');
        }
        return Promise.resolve();
      }
    }
    

表单校验方法

  • 1、使用formRef,详情请参考Form的方法API
    <a-form ref="formRef" :model="formState"> // 1 form上绑定ref
    import { FormInstance } from 'ant-design-vue'  // 2 引入ts类型
    const formRef = ref<FormInstance>() // 3 定义变量
    
    formRef.value?.validate().then(() => {}).catch(() => {}) // 4 使用校验
    
  • 2、使用 useForm,详情请参考useForm的参数说明
  • 常用方法,详情可参考各自的API
    • validatevalidateFields 触发表单验证
    • resetFields 重置整个表单
    • clearValidate移除表单校验效果

其他补充

隐藏必填红星

  • 不希望展示必填红星时,可以添加hide-required-mark参考 Form-API
  <a-form
    :model="formModel"
     :rules="formRules"
     hide-required-mark  // 新增该属性
   >

表单规则不生效

如果你确认校验规则写的没有问题,但该条规则就是不生效。请检查下你表单项绑定的值是否一致,步骤:

  • 1 先确认你form表单 绑定的数据对象
  • 2 确认表单输入框绑定的值,是否是form数据源中的数据
  • 3 确认name是该条表单项中输入框所绑定的值,名称需要一致哦
<template>
  <a-form
    :model="formState"  // 1 先确认你form表单 绑定的数据对象
  >
    <a-form-item
      label="Username"
      name="username"  // 3 确认name是该条表单项中输入框所绑定的值,名称需要一致哦
      :rules="[{ required: true, message: 'Please input your username!' }]"
    >
      <a-input v-model:value="formState.username" /> // 2 确认表单输入框绑定的值,是否是form数据源中的数据
    </a-form-item>
  </a-form>
</template>