如何自定义yup验证消息



我看到的大多数答案都是在定义模式时自定义yup验证消息,例如

const personSchema = yup.object().shape({
firstName: yup.string().required('First name is a required field'),
lastName: yup.string().required('Last name is a required field'),
});

但是,如果我想自定义默认验证消息本身,该怎么办?例如,所需字段应始终呈现固定字符串";必填字段";。

您可以使用yup中的setLocale函数,如下所示:

import * as Yup from 'yup';
Yup.setLocale({
mixed: {
required: 'Required Field',
},
});

有关详细信息,请查看文档:https://github.com/jquense/yup

使用自定义区域设置词典部分就是您所需要的。

您不需要做太多。只需在所需函数中包含所需的自定义消息。您还可以为正则表达式模式包含单独的消息

fname: yup
.string()
.required('Please enter your first name *')
.matches(
/^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/,
"Enter valid first name !"
),

我发现接受的答案是正确的,但在某些情况下可能是不完整的。将光标放置到字段中并从中跳出来可以触发Yup";类型错误";。

默认的Yup类型错误是一个冗长且不利于用户的错误;(

我将AndreasT的答案扩展为:

const personSchema = yup.object().shape({
firstName: yup.string().required().typeError('first name is a required field'),
lastName: yup.string().required().typeError('Last name is a required field'),});

最新更新