首页 > 解决方案 > 是的,自定义错误消息不在 ValidationError 对象中

问题描述

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

这是代码框。

我究竟做错了什么?我正在这样做,如图所示。

标签: javascriptvalidationyup

解决方案


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

推荐阅读