yup自定义错误消息不在ValidationError对象中

时间:2020-05-04 18:30:18

标签: javascript validation yup

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

Here's the codesandbox.

我在做什么错? I'm doing it as shown here.

1 个答案:

答案 0 :(得分:1)

您应该使用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();