hapijs / joi

The most powerful data validation library for JS
Other
20.94k stars 1.51k forks source link

Add way to pass labels on validate #3055

Open leandroluk opened 1 week ago

leandroluk commented 1 week ago

Runtime

node, browser

Runtime version

17+

Module version

17+

Used with

next + react-hook-form + next-intl + joi-translation-pt-br

Any other relevant information

I'm using Joi to validate my frontend forms and this application needs to use internationalization. An example of component using this is that:

import Joi from 'joi';
import {joiResolver} from '@hookform/resolvers/joi';
import {FormProvider, useForm} from 'react-hook-form';
import {useTranslations} from 'next-intl';

type Schema = {
  email: string
  password: string
}

const schema = Joi.object<Schema>({
  email: Joi.string().required().email({ tlds: false }),
  password: Joi.string().required().min(8).max(50)
})

export const LoginForm: React.FC = () => {
    const t = useTranslations('Joi')

    const form = useForm<IRegisterUser.Data>({
      resolver: joiResolver(IRegisterUser.schema,),
      defaultValues: { email: '', password: '' }
    });

    const onSubmit = (value: Schema) => console.log(value)

    return  (
      <FormProvider {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          {/* rest of code here */}
         <button type="submit">Submit</button>
          {JSON.stringify(form.getValues(), null, 2)}
        </form>
      </FormProvider>
    )
}

For different languages ​​I will have different labels, so I expected it to be possible to pass a tuple containing the name of the fields and their new label when validating with joi, thus maintaining the consistency of the schema and ensuring new messages as needed.

What problem are you trying to solve?

Capacity to change dynamically field labels based on validate and integrate with next-intl

Do you have a new or modified API suggestion to solve the problem?

Unfortunately not...