繁体   English   中英

是的,自定义错误消息不在 ValidationError object 中

[英]yup custom error messages not in ValidationError object

是的ValidationError object没有自定义错误消息。

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

这是代码框。

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

您应该使用try / catch块来捕获异步/等待错误,例如同步代码。

您也不能直接将消息传递给number()类型 function,而是必须传递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();

使用 0.32.11 这似乎有效:

string()
      .required('Email is require')
      .email('Email is not valid')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM