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

Valibot问题:密码确认错误提示无法显示

密码匹配错误提示不显示的解决方案

问题核心

你的代码存在两个关键问题:

  • 密码匹配验证的错误未正确关联到confirmPassword字段
  • 缺少验证后将错误结果赋值给issues的核心逻辑

修正步骤

1. 调整Schema验证逻辑,绑定错误到指定字段

替换原有的forward+partialCheck写法,用Zod的object级refine直接指定错误归属的字段:

import { object, string, nonEmpty, email, minLength, refine } from 'zod';

const UserSchema = object({
    email: pipe(
        string(),
        nonEmpty('Email is required'),
        email('The email must be in the format name@example.com')
    ),
    password: pipe(
        string(),
        nonEmpty('Password is required'),
        minLength(6, 'Password must be at least 6 characters long')
    ),
    confirmPassword: pipe(
        string(),
        nonEmpty('Confirm password is required')
    ),
}).refine((data) => data.password === data.confirmPassword, {
    message: 'Passwords do not match',
    path: ['confirmPassword'] // 强制将错误关联到confirmPassword字段
});

2. 补充验证流程,赋值错误到issues

你只定义了issues但未处理验证结果,需要添加验证触发逻辑:

import { ref } from 'vue';
import { flattenErrors } from '你的错误扁平化工具'; // 如zod-form-data或自定义方法

const formData = ref({
    email: '',
    password: '',
    confirmPassword: ''
});
const issues = ref<FlatErrors<typeof UserSchema>['nested']>();

// 表单验证方法(提交时调用)
const validateForm = () => {
    const result = UserSchema.safeParse(formData.value);
    if (!result.success) {
        // 转换Zod错误为你的FlatErrors结构
        issues.value = flattenErrors(result.error.issues);
    } else {
        issues.value = undefined;
    }
};

3. 优化模板的错误显示判断

原模板会在错误数组为空时仍渲染元素,改为判断数组长度:

<template v-if="issues?.confirmPassword?.length">
    <span
        class="register__errors"
        v-for="(issue, i) in issues.confirmPassword"
        :key="i"
    >{{ issue }}</span>
</template>

额外检查项

  • 确认FlatErrors类型定义正确,nested.confirmPassword为字符串数组类型
  • 验证时确保formData的password和confirmPassword已输入(先触发必填项验证)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:37:27