You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FormKit中忽略必填字段提交表单以暂存数据?

FormKit实现完整提交验证与忽略必填暂存的方案

针对Vue3+FormKit的大型表单需求,要区分「完整提交(需全量验证)」和「暂存(忽略必填校验)」两个逻辑,可通过以下几种方式实现:

核心思路

FormKit的表单验证默认会在提交时触发全量规则校验,我们可以通过直接获取原始表单值或动态调整验证规则两种思路实现暂存逻辑,无需修改原有必填规则。

实现方案

方案一:直接获取当前表单值(最简单)

利用FormKit表单的value属性,直接拿到当前所有已填写/未填写的字段数据,完全跳过验证逻辑,适合仅需暂存数据的场景。

代码示例

<template>
  <FormKit
    ref="formRef"
    type="form"
    :schema="formSchema"
    @submit="handleFullSubmit"
  >
    <template #submit>
      <button type="submit">完整提交</button>
      <button type="button" @click="handleSave">暂存数据</button>
    </template>
  </FormKit>
</template>

<script setup>
import { ref } from 'vue'

const formRef = ref(null)

// 带必填规则的表单Schema
const formSchema = {
  fields: [
    {
      $formkit: 'text',
      name: 'username',
      label: '用户名',
      validation: 'required',
      messages: { required: '请输入用户名' }
    },
    {
      $formkit: 'email',
      name: 'email',
      label: '邮箱',
      validation: 'required|email',
      messages: { 
        required: '请输入邮箱',
        email: '邮箱格式不正确'
      }
    },
    {
      $formkit: 'textarea',
      name: 'bio',
      label: '个人简介'
    }
  ]
}

// 完整提交:依赖FormKit自带验证,验证通过才执行
const handleFullSubmit = (validatedData) => {
  // 后端提交逻辑
  console.log('提交验证通过的数据:', validatedData)
}

// 暂存逻辑:直接获取表单当前值,跳过所有验证
const handleSave = () => {
  if (!formRef.value) return
  const currentData = formRef.value.value
  console.log('暂存的当前数据:', currentData)
  // 执行暂存逻辑(如存本地/后端暂存接口)
}
</script>

方案二:动态调整验证规则(需验证已填字段格式)

如果需要对已填写的字段做格式验证(比如邮箱格式),但忽略必填要求,可以临时移除所有字段的required规则,验证后再恢复。

代码示例

<script setup>
// ... 保留上述formRef、formSchema、handleFullSubmit

const handleSaveWithPartialValidation = async () => {
  if (!formRef.value) return
  
  // 1. 备份所有字段的原始验证规则
  const originalValidations = {}
  formRef.value.fields.forEach(field => {
    originalValidations[field.name] = field.validation
    // 移除必填规则(处理多种规则组合情况)
    if (field.validation) {
      field.validation = field.validation
        .replace('required|', '')
        .replace('|required', '')
        .replace('required', '')
    }
  })

  // 2. 仅验证已修改过的字段(可选,避免空字段触发格式验证)
  await formRef.value.validate({ onlyDirty: true })
  
  // 3. 获取当前表单数据
  const currentData = formRef.value.value
  console.log('带部分验证的暂存数据:', currentData)
  // 执行暂存逻辑

  // 4. 恢复原始验证规则,不影响后续完整提交
  formRef.value.fields.forEach(field => {
    field.validation = originalValidations[field.name]
  })
}
</script>

<template>
  <!-- 模板中添加对应按钮 -->
  <button type="button" @click="handleSaveWithPartialValidation">暂存(验证已填字段格式)</button>
</template>

方案对比

  • 方案一:代码简洁,无额外验证逻辑,适合纯暂存场景,无需关心数据格式。
  • 方案二:可对已填字段做格式校验,提升数据质量,但需要处理规则备份与恢复,逻辑稍复杂。

内容的提问来源于stack exchange,提问作者silvia_aut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:37:29