【问题标题】:Yup validation for a non-required field是的,对非必填字段进行验证
【发布时间】:2021-06-22 00:14:47
【问题描述】:

我的项目中有一个配置文件创建表单,我正在使用 react-hooks-form 和 yup 库进行验证。

在表单中有一个名为 Github-Username 的字段是可选的。但是如果用户输入用户名并且应该超过 2 个字符,我想验证它。

  const schema = yup.object().shape({
    company: yup.string().min(3).required(),
    website: yup.string(),
    location: yup.string().min(2).required(),
    skills: yup.string().min(3).required(),
    githubUsername: yup.string().min(3).nullable().notRequired(),
    bio: yup.string(),
  });

  const { register, handleSubmit, errors, touched } = useForm({
    resolver: yupResolver(schema),
  });

// 表单域

        <Form.Group controlId="formBasicGusername">
          <Form.Label>Github Username</Form.Label>
          <Form.Control
            type="text"
            name="githubUsername"
            ref={register}
          />
          <span className="text-danger text-capitalize">
            {errors.githubUsername?.message}
          </span>
        </Form.Group>

这是我到目前为止编写的架构,它不适用于 githubUsername。如果它是空的,它会显示错误。我只想验证它不为空。有这方面的线索吗?

【问题讨论】:

    标签: reactjs react-hooks yup react-hook-form


    【解决方案1】:

    批准的答案是正确的,但缺少一些信息。您需要将循环依赖项添加到形状架构中

    const schema = yup.object().shape(
        {
            company: yup.string().min(3).required(),
            website: yup.string(),
            location: yup.string().min(2).required(),
            skills: yup.string().min(3).required(),
            githubUsername: yup
                .string()
                .nullable()
                .notRequired()
                .when('githubUsername', {
                    is: (value) => value?.length,
                    then: (rule) => rule.min(3),
                }),
            bio: yup.string(),
        },
        [
            // Add Cyclic deps here because when require itself
            ['githubUsername', 'githubUsername'],
        ]
    );
    

    【讨论】:

    • 这太完美了!
    【解决方案2】:
    githubUsername: yup.string().nullable().notRequired().when('githubUsername', {
      is: value => value?.length,
      then: rule => rule.min(3),
    })
    

    【讨论】:

    • 如果我使用这种语法,我得到一个错误:循环依赖。奇怪?(是的 v0.32.9)
    猜你喜欢
    • 2012-05-23
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2013-08-05
    • 2020-02-27
    • 1970-01-01
    相关资源
    最近更新 更多