Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

表单校验数字类型 #5476

Closed
5 tasks done
zuihou opened this issue Feb 5, 2025 · 1 comment
Closed
5 tasks done

表单校验数字类型 #5476

zuihou opened this issue Feb 5, 2025 · 1 comment

Comments

@zuihou
Copy link

zuihou commented Feb 5, 2025

Version

Vben Admin V5

Describe the bug?

表单配置:

export const formSchamas: VbenFormProps = {
  wrapperClass: 'grid-cols-12', // 24栅格,
  commonConfig: {
    formItemClass: 'col-span-12',
  },
  schema: [
    {
      fieldName: 'notNull',
      label: 'notNull',
      // component: 'Input',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
        allowClear: true,
      },
      rules: zod.number({
              required_error: '此项必填',
              invalid_type_error: '数据类型错误',
            }),
      formItemClass: 'col-span-4',
  }
]
}
  1. 设置组件类型为: InputNumber
  2. 首次加载进入该页面时,该组件的默认值是 undefined, 能正常提示 “此项必填”
Image
  1. 当在该字段填写为正常数字时,能正常校验
Image
  1. 在组件填写任意值后,在按键盘上的删除键,将字段的值全部删除,会提示:数据类型错误
Image

问:
有没有办法,使得删除填写的值后,校验提示为“此项必填”.

System Info

最新版

Relevant log output

Validations

@mynetfan
Copy link
Collaborator

mynetfan commented Feb 5, 2025

zod
  .number({ invalid_type_error: '类型错误' })
  .nullish()
  .refine((value) => value !== undefined && value !== null, {
    message: '字段必填',
  }),

这个问题在于antd的input-number组件删除所有内容后,值会变为null而不是undefined。zod校验时null不会视为未填写(undefined),所以可能得自行对必填进行验证。这里用nullish指示它允许null和undefined类型,之后用refine自行校验

@mynetfan mynetfan closed this as completed Feb 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants