Skip to main content

Error message customization

Default error messages can be customized for when no message is provided with a validation test. If any message is missing in the custom dictionary the error message will default to Yup's one.

import { setLocale } from 'yup';

setLocale({
mixed: {
default: 'Não é válido',
},
number: {
min: 'Deve ser maior que ${min}',
},
});

// now use Yup schemas AFTER you defined your custom dictionary
let schema = yup.object().shape({
name: yup.string(),
age: yup.number().min(18),
});

try {
await schema.validate({ name: 'jimmy', age: 11 });
} catch (err) {
err.name; // => 'ValidationError'
err.errors; // => ['Deve ser maior que 18']
}

localization and i18n​

If you need multi-language support, yup has got you covered. The function setLocale accepts functions that can be used to generate error objects with translation keys and values. These can be fed it into your favorite i18n library.

import { setLocale } from 'yup';

setLocale({
// use constant translation keys for messages without values
mixed: {
default: 'field_invalid',
},
// use functions to generate an error object that includes the value from the schema
number: {
min: ({ min }) => ({ key: 'field_too_short', values: { min } }),
max: ({ max }) => ({ key: 'field_too_big', values: { max } }),
},
});

// ...

let schema = yup.object().shape({
name: yup.string(),
age: yup.number().min(18),
});

try {
await schema.validate({ name: 'jimmy', age: 11 });
} catch (err) {
messages = err.errors.map((err) => i18next.t(err.key));
}