12

I have nested fields with number inputs and can't get the validation to work properly. Not sure if this is a problem with formik or yup / how the validation schema is declared but I'll start asking here.

In the example I have two fields which represents numbers and defaults to empty string. The validation works for the first fields but I can not get it to behave the same for the nested field. When I touch the field but don't type anything it returns :

social.facebook must be a number type, but the final value was: NaN (cast from the value "").

Example: codesandbox

1 Answer 1

16

Seems it's problem with formik , with nested field validation ! when it's number and value is initialized with empty string this last throw that error

you can workaround it by transforming into null when it's an empty string , then set it as nullable inside validationSchema as below

validationSchema={Yup.object().shape({
    email: Yup.number(),
    social: Yup.object().shape({
      facebook: Yup.number()
                   .transform((value, originalValue) => originalValue.trim() === "" ? null: value)
                   .nullable()
    })
})}

See codeSandbox

For further validation , if you want special message for only number add .typeError("your message")

as below :

validationSchema={Yup.object().shape({
    email: Yup.number().typeError("must be a number"),
    social: Yup.object().shape({
      facebook: Yup.number()
                   .typeError("must be a number")
                   .transform((value, originalValue) => originalValue.trim() === "" ? null: value)
                   .nullable()
    })
})}

PS: you can set initial values as , null for numbers and add .nullable() to schenma .

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.