0

My problem is I add validation schema on my formik form but the required() validation does not work if I put default("mmm") value

<Formik 
 initialValues={validtionShema.cast()} 
validationSchema={validtionShema} >

</Formik>

const validtionShema = Yup.object()
  .shape({
    name: Yup.string().default("@").required(),
    phone: Yup.number().integer().positive().min(1).default(0555).required(),
  })

so here required does not work if I remove default it will gonna work but in my case i should add a default value

the validation schema will work as expected

1 Answer 1

0

This problem is really related to Formik. There are quite a few issues on this topic in their repository. I solved this problem by overriding the required method

import { isEmpty } from 'lodash';

yup.addMethod(yup.number, 'required', function (message?: string) {
  return this.test(
    'required',
    message ?? 'common.validation.required',
    function (value, testContext) {
      const options = testContext.options as Record<string, string>;
      const defaultValue = testContext.schema.spec.default;
      const originalValue = !isEmpty(options) ? options['originalValue'] : value;
      const finalValue = typeof defaultValue === 'number' ? originalValue : value;

      return finalValue !== '' && finalValue !== null && finalValue !== undefined;
    },
  );
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.