lazyCoder
lazyCoder

Reputation: 589

Yup validation for a non-required field

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

Upvotes: 21

Views: 36369

Answers (2)

Mathieu Doyon
Mathieu Doyon

Reputation: 420

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'],
    ]
);

Upvotes: 40

Mikhail Grechka
Mikhail Grechka

Reputation: 735

githubUsername: yup.string().nullable().notRequired().when('githubUsername', {
  is: value => value?.length,
  then: rule => rule.min(3),
})

Upvotes: 10

Related Questions