Parameterisation of yup translation - next.js

26 Views Asked by At

I currently have this translation in the schema:

.json file:

{"register.validation.first.name": "First name may contain letters, numbers, spaces and some punctuation characters only, and must not exceed 40 characters"}

and use it like:

import * as yup from 'yup';

export const FIRST_NAME_REGEXP =
  /^(?!\s)(?!.*\s{3})(?!.*(http|www))(?!.*[&$=+#|{}()£[\]<>?!:;@"%^*\p{Extended_Pictographic}]).{1,40}$/iu;

export const RegisterSchema = yup.object({
  firstName: yup
    .string()
    .required('register.invalid.first.name')
    .matches(FIRST_NAME_REGEXP, 'register.validation.first.name')
});

How can I parameterise the value '40' in the translation text?

I need changing it like this:

{"register.validation.first.name": "First name may contain letters, numbers, spaces and some punctuation characters only, and must not exceed {{numChar}} characters"}

but what should I change here? -> .matches(FIRST_NAME_REGEXP, 'register.validation.first.name')

I have tried integrating i18n translations but does not work with yup, and yes I need to use yup.

Unable to find how to do it, if possible at all (seems like it's not).

1

There are 1 best solutions below

0
Calix On BEST ANSWER

I created a function that generates a yup schema with a dynamic character limit. When the limit is exceeded, it produces a translated error message using the matches() method.

import i18n from 'i18next'; //Assuming the use of the i18next library


const createValidationSchema = (maxCharacters) => {
  
  const firstNameRegexp = new RegExp(`^(?!\\s)(?!.*\\s{3})(?!.*(http|www))(?!.*[&$=+#|{}()£[\\]<>?!:;@"%^*\\p{Extended_Pictographic}]).{1,${maxCharacters}}$`, 'iu');
  
  //dynamically generating error messages
  const errorMessage = (key, params) => i18n.t(key, params);

 
  return yup.object({
    firstName: yup
      .string()
      .required(errorMessage('register.invalid.first.name'))
      .matches(firstNameRegexp, () =>
        errorMessage('register.validation.first.name', { numChar: maxCharacters })
      )
  });
};

//Example of use
const RegisterSchema = createValidationSchema(40);

In this code, the createValidationSchema function takes maxCharacters as an argument, and based on this, dynamically generates the regular expression and the translated error message.