最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Formik - Nested field validation - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Oct 10, 2019 at 9:22 Bourbia Brahim 14.7k4 gold badges43 silver badges54 bronze badges asked Oct 10, 2019 at 9:08 seberikseberik 4151 gold badge6 silver badges13 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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 .

发布评论

评论列表(0)

  1. 暂无评论