Problem
The yupResolver loses some nested errors
Background
I have a schema for validating dates. The input format is an object {day, month, year}
. This is because my input form has three separate fields.
The intention is that when the error is due to a specific field, I can highlight that field in the UI. There are some validation conditions that apply to the whole date, and for those I will highlight all three fields.
Details
The schema (simplified slightly):
yup
.object({
day: yup
.number()
.max(31, "Day of birth must be in range 1-31"),
month: yup
.number()
.max(12, "Month of birth must be in range 1-12"),
year: yup
.number()
.required("Year of birth is required")
})
.test({
name: "is-valid-date",
message: "Please enter a valid date.",
test: value => moment(value).isValid(),
})
When the input value fails validation on both a specific field, and on the whole value, the errors
object that I receive back contains only the outer error.
i.e. for value {day: 1, month:999, year: 1993 }
, the resulting error from yup includes both "Month of birth must be in range 1-12"
and "Please enter a valid date."
but the errors object returned by yupResolver
only contains "Please enter a valid date."
Root cause?
I think this is due to the order of the keys in the object that yup returns, and a bug in https://github.com/react-hook-form/react-hook-form/blob/V6/src/logic/transformToNestObject.test.ts.
This transform tool has unexpected behaviour depending on the order of the input.
I have demonstrated this in a PR:
react-hook-form/react-hook-form#1722
The first test passes. The second loses information. The only difference is the ordering of keys in the input.
I am not sure if the fix should be in transformToNestObject, because that may have other dependencies.