18

I have a profile creation form in my project for which i am using react-hooks-form and yup library for validation.

In the form there is one field named Github-Username which is optional. But i want to validate it if users enters the username and it should be more than 2 characters, something like that.

  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 Field

        <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>

This is the schema i have written so far, which is not working for githubUsername. It showing the error if it's empty. I want to validate only if it's not empty. Any leads on this?

enter image description here

skyboyer
  • 22,209
  • 7
  • 57
  • 64
lazyCoder
  • 499
  • 1
  • 4
  • 17

2 Answers2

32

The approved answer is right but missing a bit of information. you need to add cyclic dependencies to the shape schema

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'],
    ]
);
Mathieu Doyon
  • 340
  • 3
  • 3
9
githubUsername: yup.string().nullable().notRequired().when('githubUsername', {
  is: value => value?.length,
  then: rule => rule.min(3),
})
Mikhail Grechka
  • 717
  • 2
  • 10
  • 12
    I get an Error: Cyclic dependency if I use this syntax. Weird (yup v0.32.9) – pom421 Jun 21 '21 at 15:35
  • This does not work, cyclic dependency – Dave Funk Sep 16 '22 at 20:59
  • while i appreciate the code suggestion, if the person has asked a question, maybe just seeing the code is not enought. i'd find it prefferable for there to be some comments explaining what's happening because depending on the askers profiency, just reading might not be enough – Leinil Nov 17 '22 at 19:35