jquense / yup

Dead simple Object schema validation
MIT License
22.96k stars 936 forks source link

Skip entire validation schema if a certain condition is met #1785

Open TamirCode opened 2 years ago

TamirCode commented 2 years ago

I want to skip the entire validation schema under a certain condition. So if I have

email: yup
    .string('Enter your email')
    .email('Enter a valid email')
    .required('Email is required'),

I want to be able to add to it something like .validateSchemaIf(1 + 1 === 2) and so the 3 validations will run only if that condition is true. If the condition is false, then all the specific validations will be ignored and it will pass the entire validation test.

Context: I have a simplified MUI formik boilerplate code and I want formik to skip validation for the fields that are equal to their initial value at any time. I have gone down the rabbit hole in trying to achieve this simple functionality with Formik and unfortunately there isn't a way. So I have decided to try and do this via Yup validation. https://codesandbox.io/s/formik-sandbox-forked-gyd0zz?file=/src/App.js

afilp commented 2 years ago

Can't the lazy functionality help in this case? By adding the conditional inside the lazy function and choose what to do there?

TamirCode commented 2 years ago

I tried using lazy and when for this, but I can't get it to work no matter what. If someone could give me an example I would appreciate it greatly

Ak-patel commented 2 years ago
email: Yup.string()
        .when("condition", {
            is: true,
            then: email: Yup
                .string('Enter your email')
                .email('Enter a valid email')
                .required('Email is required'),
          }),

You can give here 'condition' certain conditions for this validation

TamirCode commented 2 years ago
email: Yup.string()
        .when("condition", {
            is: true,
            then: email: Yup
              .string('Enter your email')
              .email('Enter a valid email')
              .required('Email is required'),
          }),

You can give here 'condition' certain conditions for this validation

there is nothing i can do to make it work, since the condition part accepts only a string (name of key), and if I put a key with that name and give it a condition such as condition: true, then it doesn't work either, since i think its meant to be only previous Yup validator keys . Thanks anyways for the help , let me know if u find a solution to this

jquense commented 2 years ago

@TamirCode can you post specifically what you are trying to accomplish, and what you've tried. You keep saying things don't work but we can't see what your doing so can't possibly provide helpful feedback