vue ant form validate如何对数组下的表单校验

发布于:2024-04-25 ⋅ 阅读:(20) ⋅ 点赞:(0)

问题

使用Ant Design Vue校验表单时,通过validateFields,但是如何一个数组内部的校验呢?

效果图:

在这里插入图片描述

实现方式:

通过 v-for 循环渲染:name="[]"实现,我们直接看代码。

<template>
  <a-form
    ref="formRef"
    :model="formState"
    :label-col="{ style: { 'width': '150px' } }"
    :wrapper-col="{ style: { 'max-width': '350px' } }"
  >
    <!-- 其他表单项 -->
	<a-form-item>
	    <template #label>
	      path
	      <a-tooltip title="提示:。。。" >
	        <question-circle-outlined />
	      </a-tooltip>
	    </template>
	    <a-form-item
	      v-for="(item, index) in formState.path"
	      :key="index"
	      label="" // 不展示 label 标签的文本
	      :name="['path', index, 'value']"  // 通过 :name="[]" 将数组中各个数据参数,绑定到 form 表单校验中
	      :colon="index === 0 ? true : false" // 是否显示 label 后面的冒号
	      :rules="[{ required: true, trigger: 'blur', min:1, max:150, message: '请输入path'}]"
	      style="width: 500px;"
	    > 
	      <a-space>
	        <a-input 
	          style="width: 350px;" 
	          v-model:value="item.value" 
	          placeholder="请输入请求路径,可添加多个" 
	         />
	        <PlusCircleOutlined
	          v-if="formState.path.length === index + 1"
	          :disabled="formState.path.length === 1"
	          @click="addPath()"
	        />
	        <MinusCircleOutlined
	          v-if="formState.path.length > 1"
	          :disabled="formState.path.length === 1"
	          @click="removePath(item)"
	        />
	      </a-space>
	    </a-form-item>
	</a-form-item>
    <!-- 其他表单项 -->
	
	<a-form-item 
      name="type" 
      label="是否开启" 
      :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
    >
      <a-radio-group 
        v-model:value="formState.type" 
        @change="handleChangeType">
        <a-radio :value="2"></a-radio>
        <a-radio :value="1"></a-radio>
      </a-radio-group>
    </a-form-item>
        
    <a-form-item>
      <a-button type="primary" @click="handleSubmit">
        Submit
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { MinusCircleOutlined, PlusCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'

const formRef = ref<FormInstance | any>()
const formState = ref({ 
	path: [{value: ''}],
	type: 1
})

const removePath = (item: any) => {
  const index = props.formState.path.indexOf(item)
  if (index !== -1) {
    props.formState.path.splice(index, 1)
  }
}
const addPath = () => {
  props.formState.path.push({
    value: ''
  })
}

const validateUri = async (_rule: any, value: string) => {
  if (!/^(\*|\/\*|\/)/.test(value)) {
    return Promise.reject('path 需要以“*”、“/*”、“/”开始,不能包含特殊字符')
  } else {
    return Promise.resolve()
  }
}

function handleSubmit() {
  formRef.value && (formRef.value).validate().then((res: any) => {
    // todo
  });
}
</script>

到此,一个数组下的表单校验开发就完成了。

如何单独只对数组校验,或者数组中某一个校验

上面 formRef.value.validate() 是通过 ref 对整个表单的校验,那么如果我只是想实现单个校验呢?

function handleChangeType () {
  formRef.value && (formRef.value).validate(['mobile', 'captcha'])
}

但是针对对:name=“”这种数组方式,如何处理呢?

百度查询了很多,Chatgpt也尝试了:

// 错误方式:
function handleChangeType () {
	formRef.value && (formRef.value).validate(['path[0].value', 'path[1].value']) // 无反应
}

但是,这些都是错误的,并没有生效,真正生效的是下面这个:

// 正确方式
function handleChangeType () {
	// 对数据中的某个数据校验
	formRef.value && (formRef.value).validate([['path', 0, 'value'], ['path', 1, 'value']])
	// 对数据所有数据校验
    const regxPaths = formState.value.path.map((item:any, index:number) => ['path', index, 'value'])
    formRef.value && (formRef.value).validate(regxPaths)
}

文章到此结束,希望对你有所帮助!