Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik - Nested field validation

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

like image 353
seberik Avatar asked Oct 10 '19 09:10

seberik


1 Answers

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 .

like image 91
Spring Avatar answered Nov 06 '22 19:11

Spring