yup 翻译的参数化 - next.js

问题描述 投票:0回答:1

我目前在架构中有这个翻译:

.json 文件:

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

并像这样使用它:

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')
});

如何在翻译文本中参数化值“40”?

我需要像这样改变它:

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

但是我应该在这里改变什么? -> .matches(FIRST_NAME_REGEXP, 'register.validation.first.name')

我尝试过集成 i18n 翻译,但无法与 yup 一起使用,是的,我需要使用 yup。

无法找到如何做到这一点,如果可能的话(似乎不是)。

reactjs validation next.js translation yup
1个回答
0
投票

我创建了一个函数,可以生成具有动态字符限制的

yup
模式。当超出限制时,它会使用
matches()
方法生成翻译后的错误消息。

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);

在这段代码中,

createValidationSchema
函数以
maxCharacters
为参数,并基于此动态生成正则表达式和翻译后的错误消息。

© www.soinside.com 2019 - 2024. All rights reserved.