jquense / yup

Dead simple Object schema validation
MIT License
22.72k stars 925 forks source link

Validation error does not occur even if test is written for object #2229

Closed lbk-yuuki-nakamura closed 1 month ago

lbk-yuuki-nakamura commented 2 months ago

This is the formik and yup definition in package.json

"formik": "^2.2.9",
"yup": "^1.4.0",

As shown below, running a test on a single field usually results in a validation error. Therefore, there is no problem in building the environment.

const formik = useFormik({
  initialValues: { hoge: false },
  validationSchema: Yup.object({
    hoge: Yup.boolean().test('e-key', 'error message', () => { return false }),
  }),
  onSubmit: () => {
    console.log('=====SUBMIT=====');
  },
});

However, if validation causes an error for object as shown below, it will be ignored and onSubmit will be executed.

const formik = useFormik({
  initialValues: { hoge: false },
  validationSchema: Yup.object({
    hoge: Yup.boolean()
  }).test('e-key1', 'error', () => { return false }),
  onSubmit: () => {
    console.log('=====SUBMIT=====');
  },
});

The same is true if you do the following

const formik = useFormik({
  initialValues: { hoge: false },
  validationSchema: Yup.object(). shape({
    hoge: Yup.boolean()
  }).test('e-key1', 'error', () => { return false }),
  onSubmit: () => {
    console.log('=====SUBMIT=====');
  },
});

In the sample, validation is checked for one field.

Actually, I would like to refer to several boolean fields and generate an error across fields, such as ``If all boolean fields are false, display an error in all fields.''

jquense commented 2 months ago

I can't provide support for formik. If you can reduce the problem to just yup i'm happy to help.

lbk-yuuki-nakamura commented 1 month ago

thank you.

I tried to run Yup validation, but it turned out to be an error. We can assume that this is a problem with formik.

const schema = Yup.object({
  hoge: Yup.boolean(),
}).test('e-key1', 'error', () => {
  return false;
});

schema
  .validate({ hoge: true })
  .then((value) => {
    console.log('Validation succeeded:', value);
  })
  .catch((err) => {
    console.log('Validation failed:', err.errors);
  });