1. 程式人生 > 其它 >Antd之表單校驗

Antd之表單校驗

使用Antd進行表單校驗,程式碼如下:

<template>
  <a-form
    :model="formState"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    ref="newFormRef"
    autocomplete="off"
  >
    <a-form-item
      label="模板名"
      name="name"
      has-feedback
      :rules="[{ required: true, message: '請輸入模板名' }]"
> <a-input v-model:value="formState.name" /> </a-form-item> <a-form-item :wrapper-col="{ span: 14, offset: 10 }"> <a-button type="primary" html-type="submit" @click="onSubmit">確認</a-button> </a-form-item> </a-form> </template>

即設定表單的ref值,在form-item中設定校驗規則,注意要設定form-item的name值。

然後在提交表單時根據ref值對錶單進行校驗,程式碼如下:

methods: {
  onSubmit(){
    this.$refs.newFormRef.validate().then(() => {
      console.log("submit!", this.formState, toRaw(this.formState));
      this.$emit("afterSavingToTemplate");
    });
  }
}

即可。