Пользовательские сообщения об ошибках не в объекте ValidationError - PullRequest
0 голосов
/ 04 мая 2020

Объект yup ValidationError не имеет пользовательских сообщений об ошибках.

let data = {
    foo: "aaa"
}

let schema = 
    yup.object().shape({
        foo: yup.number().integer('Custom "must be a number" error message!')
    });

try {

    let validated = await schema.validate(data, { abortEarly: false })

} catch (err) {
    console.log(err.errors[0]) // foo must be a `number` type, but the final value was: `NaN`
    console.log(err.inner[0].message) // foo must be a `number` type, but the final value was: `NaN`
}

Я должен получить Custom "must be a number" error message! при err.inner[0].message.

Вот коды и поле.

Что я делаю не так? Я делаю это, как показано здесь.

1 Ответ

0 голосов
/ 04 мая 2020

Вы должны использовать блок try / catch для перехвата асинхронных / ожидающих ошибок, таких как синхронный код.

Также вы не можете напрямую передать сообщение в функцию типа number(), вместо этого вы должны передать typeError

import * as yup from "yup";

const fn = async () => {
  let data = {
    foo: "a"
  };

  let schema = yup.object().shape({
    foo: yup.number().typeError("Custom not a number message!")
  });

  try {
    await schema.validate(data);
  } catch (e) {
    console.log(JSON.stringify(e));
  }
};

fn();
...