javascript - 是的,自定义错误消息不在 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
。
我究竟做错了什么?我正在这样做,如图所示。
解决方案
您应该使用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();
推荐阅读
- coq - 我可以在 Coq 中使用函数作为构造函数吗?
- react-native-ui-kitten - React Native,UI Kitten Input 默认和 onFocus 状态下的自定义样式
- c - 无法使用 C 中的管道发送大于 64 KB 的数据
- javascript - nodejs静态路由和文件的问题
- python - 为 Ipython wigets 设置盒子的大小
- python - 列出 AWS 账户中的所有 EBS 卷
- ios - 即使使用 reloadData,UICollectionView 也不会重新加载搜索结果
- linux - 使用 /var/lib/ieee-data/oui.txt 搜索 MAC 制造商信息
- python - 来自 svg 的 NetworkX node_shape
- python - 无法将时间字符串从 csv 转换为 datetime