Библиотека Yup содержит встроенный набор стандартных сообщений об ошибках для каждого типа проверки. Эти сообщения автоматически используются при вызове методов валидации, если разработчик не указал собственный текст ошибки.
import * as yup from 'yup';
const schema = yup.string().required();
schema.validate('')
.catch(err => {
console.log(err.message);
});
Результат:
this is a required field
Сообщение формируется автоматически на основе типа проверки.
Каждый валидатор внутри Yup содержит:
Например:
yup.string().min(5)
При ошибке используется шаблон:
this must be at least 5 characters
Число 5 подставляется автоматически.
const schema = yup.string().required();
Ошибка:
this is a required field
const schema = yup.string().min(3);
Ошибка:
this must be at least 3 characters
const schema = yup.string().max(10);
Ошибка:
this must be at most 10 characters
const schema = yup.string().email();
Ошибка:
this must be a valid email
const schema = yup.string().url();
Ошибка:
this must be a valid URL
const schema = yup.string().matches(/[A-Z]/);
Ошибка:
this must match the following: "/[A-Z]/"
const schema = yup.string().length(8);
Ошибка:
this must be exactly 8 characters
const schema = yup.string().lowercase();
Ошибка:
this must be a lowercase string
const schema = yup.string().uppercase();
Ошибка:
this must be a upper case string
const schema = yup.string().trim();
Ошибка:
this must be a trimmed string
const schema = yup.number().required();
Ошибка:
this is a required field
const schema = yup.number().min(18);
Ошибка:
this must be greater than or equal to 18
const schema = yup.number().max(99);
Ошибка:
this must be less than or equal to 99
const schema = yup.number().positive();
Ошибка:
this must be a positive number
const schema = yup.number().negative();
Ошибка:
this must be a negative number
const schema = yup.number().integer();
Ошибка:
this must be an integer
const schema = yup.number().moreThan(10);
Ошибка:
this must be greater than 10
const schema = yup.number().lessThan(50);
Ошибка:
this must be less than 50
const schema = yup.boolean();
Ошибка:
this must be a `boolean` type
const schema = yup.boolean().oneOf([true]);
Ошибка:
this must be one of the following values: true
const schema = yup.array().required();
Ошибка:
this is a required field
const schema = yup.array().min(2);
Ошибка:
this field must have at least 2 items
const schema = yup.array().max(5);
Ошибка:
this field must have less than or equal to 5 items
const schema = yup.array().length(3);
Ошибка:
this field must have 3 items
const schema = yup.object();
Ошибка:
this must be a `object` type
const schema = yup.date().required();
Ошибка:
this is a required field
const schema = yup.date().min(new Date(2025, 0, 1));
Ошибка:
this field must be later than 2025-01-01T00:00:00.000Z
const schema = yup.date().max(new Date(2025, 11, 31));
Ошибка:
this field must be at earlier than 2025-12-31T00:00:00.000Z
Yup автоматически пытается преобразовывать значения.
Пример:
const schema = yup.number();
schema.validate('abc')
.catch(err => {
console.log(err.message);
});
Ошибка:
this must be a `number` type, but the final value was: NaN
Метод label() заменяет слово this в
ошибках.
const schema = yup
.string()
.label('Имя')
.required();
Ошибка:
Имя is a required field
Yup использует специальные плейсхелдеры:
| Плейсхолдер | Значение |
|---|---|
${path} |
имя поля |
${value} |
текущее значение |
${min} |
минимальное значение |
${max} |
максимальное значение |
${length} |
длина |
${values} |
список допустимых значений |
${label} |
label() |
const schema = yup.string().min(5);
Внутренний шаблон:
${path} must be at least ${min} characters
После обработки:
this must be at least 5 characters
Позволяет заменить стандартную ошибку типа.
const schema = yup
.number()
.typeError('Возраст должен быть числом');
const schema = yup.number();
schema.validate('hello');
Ошибка:
this must be a `number` type
const schema = yup
.number()
.typeError('Неверный формат числа');
schema.validate('hello');
Ошибка:
Неверный формат числа
default() не влияет на текст ошибки напрямую, но может
предотвратить её появление.
const schema = yup
.string()
.default('guest')
.required();
Если значение отсутствует, используется "guest".
const schema = yup.object({
user: yup.object({
email: yup.string().email().required()
})
});
Ошибка содержит путь:
user.email
schema.validate(data)
.catch(err => {
console.log(err.path);
});
Результат:
user.email
Массив всех ошибок.
schema.validate(data, { abortEarly: false })
.catch(err => {
console.log(err.errors);
});
Пример:
[
'Email is required',
'Password too short'
]
Содержит подробную информацию обо всех ошибках.
schema.validate(data, { abortEarly: false })
.catch(err => {
console.log(err.inner);
});
Каждый объект включает:
По умолчанию Yup останавливается после первой ошибки.
schema.validate(data);
Для получения всех ошибок:
schema.validate(data, {
abortEarly: false
});
const schema = yup.object({
email: yup.string().email().required(),
password: yup.string().min(8).required()
});
schema.validate({
email: 'wrong',
password: ''
}, {
abortEarly: false
})
.catch(err => {
console.log(err.errors);
});
Результат:
[
'email must be a valid email',
'password must be at least 8 characters',
'password is a required field'
]
Yup поддерживает глобальную замену сообщений через
setLocale().
import { setLocale } from 'yup';
setLocale({
mixed: {
required: 'Поле обязательно'
}
});
setLocale({
string: {
min: 'Минимум ${min} символов',
max: 'Максимум ${max} символов'
}
});
setLocale({
number: {
min: 'Минимальное значение: ${min}',
max: 'Максимальное значение: ${max}'
}
});
setLocale({
array: {
min: 'Минимум ${min} элементов'
}
});
setLocale({
mixed: {
default: 'Поле заполнено неверно',
required: 'Поле обязательно'
},
string: {
email: 'Некорректный email',
min: 'Минимум ${min} символов'
},
number: {
min: 'Минимальное значение ${min}'
}
});
Yup делит сообщения на группы:
| Категория | Назначение |
|---|---|
| mixed | базовые проверки |
| string | строки |
| number | числа |
| date | даты |
| object | объекты |
| array | массивы |
| boolean | булевы значения |
Используется как универсальная ошибка.
setLocale({
mixed: {
default: 'Ошибка валидации'
}
});
setLocale({
mixed: {
required: 'Поле обязательно'
}
});
setLocale({
mixed: {
oneOf: 'Недопустимое значение'
}
});
setLocale({
mixed: {
notOneOf: 'Значение запрещено'
}
});
Без локализации все ошибки будут англоязычными.
Некоторые сообщения неудобны для интерфейсов:
this must be a `number` type
Стандартные ошибки не учитывают бизнес-логику приложения.
Можно локализовать только часть сообщений.
setLocale({
mixed: {
required: 'Обязательное поле'
}
});
Остальные ошибки останутся стандартными.
schema.validate(value)
.catch(err => {
console.log(err.message);
});
Все ошибки Yup представлены объектом
ValidationError.
import { ValidationError } from 'yup';
{
name: 'ValidationError',
path: 'email',
type: 'email',
value: 'wrong',
message: 'email must be a valid email'
}
В режиме strict() Yup отключает автоматическое
преобразование типов.
const schema = yup.number().strict();
Теперь строка "5" не станет числом.
Ошибка:
this must be a `number` type
const schema = yup.string().nullable();
null перестаёт считаться ошибкой типа.
const schema = yup.string().defined();
Ошибка:
this must be defined
const schema = yup.string().nonNullable();
Ошибка при null:
this cannot be null
Полезно анализировать объект ошибки полностью.
schema.validate(data)
.catch(err => {
console.log(err);
});
schema.validate(data)
.catch(err => {
console.log(err.params);
});
Пример:
{
min: 5
}
Обычно используются:
err.message
или:
err.errors
Наиболее распространённый подход:
setLocale({
mixed: {
required: 'Обязательное поле'
},
string: {
email: 'Некорректный email'
}
});
Для интерфейсов чаще всего:
this;label() для названий полей.const schema = yup.object({
email: yup
.string()
.label('Email')
.email()
.required(),
age: yup
.number()
.label('Возраст')
.min(18)
});
Ошибки:
Email must be a valid email
Возраст must be greater than or equal to 18