i faced a problem in React Hook Form while using Yup for validation for typeScript conflicts.
lets assume we have a form that is for both edit and insert(Add new data). this form have name
and id
and they both are required. so we while make Yup schema like bellow.
const schema = Yup.object().shape({
name: Yup.string().required(),
id:Yup.number().required(),
})
then we should assign values to react hook form as we have edit mode. so we do like this:
const values = isEditMode ? {name: editValue.name , id: editValue.id} : {name: '', id: null}
here we will face the problem. name cant be null
cause we made it required. i cant leave it be and don’t write it in values cause it will be undefined
and again we get error. also can’t give it a dummy number like -1 or make id nullable()
in schema, cause although it the typeScript error will go away, but if user forget to fill Id input, then it won’t show the validation error that it is required as it has -1 value or it can be null
.
what should i do in this case that solve the typeScript Error for value resolver, while the validation works fine too.