jquense / yup

Dead simple Object schema validation
MIT License
22.74k stars 927 forks source link

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

Open TamirCode opened 1 year ago

TamirCode commented 1 year 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 1 year 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 1 year 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 1 year 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 1 year 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 1 year 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