Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 701
lazyCoder Avatar asked Mar 25 '21 08:03

lazyCoder


People also ask

Can I use Yup without Formik?

Yes, you can use Yup without Formik, and you can use Formik without Yup. However, if you're building a React application, form validation becomes much easier when you use a Formik component and Yup email validation together.

How do you validate two fields that depend on each other with Yup?

Solution: const yup = require('yup') const { setLocale } = yup setLocale({ mixed: { notType: 'the ${path} is obligatory', required: 'the field ${path} is obligatory', oneOf: 'the field ${path} must have one of the following values: ${values}' } }) const myNameSchema = yup. object(). shape({ first_name: yup.

What is shape in Yup?

yupobject documentation. Basically passing the schema to shape is just the long-form of passing it to the object constructor. Shape does however offer the benefit of chaining and overloading definitions in later chained methods. See yup.shape documentation. Follow this answer to receive notifications.

How to validate form fields using Yup?

First, we will create new schema object with Yup. This schema will define all values (form fields) we want to validate. These values will be firstName, lastName, email, password and website. We will want all these values to be string () and required (). We will specify the email value to match email format, with email ().

Why does Yup stop after first error during validation?

This means that if Yup encounters any error during validation it will not stop the process. It will stop only after all form values are validated. Only then will it return the status for all specified values (form fields). Without this option, Yup would stop after first error and return only that.

What is Yup?

What is Yup? Yup is a JavaScript object schema validator. Lets understand the above definition with an example. Consider everday common feature of login form with fields "username" and "password". Before submitting form we want to verify that user has entered all fields.

How to solve the problem with form validation?

There are multiple ways to solve the problem with form validation. The most basic and also most accessible is the native way. This is the validation provided by browsers. This validation works well if you use correct field types and don’t need any customization. Then, there are bigger, all-in-one solutions, such as Formik.


2 Answers

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'],
    ]
);
like image 152
Mathieu Doyon Avatar answered Nov 15 '22 11:11

Mathieu Doyon


githubUsername: yup.string().nullable().notRequired().when('githubUsername', {
  is: value => value?.length,
  then: rule => rule.min(3),
})
like image 35
Mikhail Grechka Avatar answered Nov 15 '22 12:11

Mikhail Grechka