react-hook-form / resolvers

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS
https://react-hook-form.com/
MIT License
1.77k stars 161 forks source link

Providing different names for different pattern validations doesn't work with hookform/resolvers #539

Closed mumispb closed 1 year ago

mumispb commented 1 year ago

Describe the bug Providing a name on string.pattern() does not return an error key with the appropriate name provided.

To Reproduce Steps to reproduce the behavior:

  1. Create a validation like:

joi.string().pattern(Regex, 'name1').messages({ 'string.pattern.name1': 'Name 1 error message' }) or

joi.string().pattern(Regex, { name: 'name1' }).messages({ 'string.pattern.name1': 'Name 1 error message' })

  1. Check that you get the default validation message and not the custom provided one.
  2. I have debugged it with:
resolver: (data, context, options) => {
      console.log(data, context);
      console.log(joiResolver(joiSchema)(data, context, options));
      return joiResolver(joiSchema)(data, context, options);
}

and have confirmed the error key that is provided is always 'string.pattern.name', without the custom name provided.

I have been able to get the expected behavior while validating manually (not using the resolver).

Codesandbox link (Required) https://codesandbox.io/s/musing-shaw-btb5ps?file=/src/App.tsx

Expected behavior Expected to be able to give different messages for different patterns with 'string.pattern.nameProvided'.

Desktop (please complete the following information):

jorisre commented 1 year ago

Hi @mumispb thanks for the feedback. Can I see how you validate manually without the resolver?

mumispb commented 1 year ago

Hi @jorisre I apologize, the manual validation way does not automatically provide errors with specific keys like 'string.pattern.fieldName1', 'string.pattern.fieldName2', etc. They way I did actually involved using the context provided by the manual validation, like:

const manualValidation = joiSchema.validate(values)

and filtering out what I wanted from manualValidation.error.details array and grabbing the .context value.

That context provides me with the actual validation pattern name that was triggered, which I can use to search inside a separate array of possible errors. It seems I can do the same with the resolvers using the ref.name that is inside the errors object as in formState.errors[fieldName].ref.name, right?

jorisre commented 1 year ago

This is not a problem since Joi doesn't provide the names you assign to Joi errors. Unfortunately, obtaining names from Joi validation is not possible, which can be seen as a limitation.