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
。
我在做什么错? I'm doing it as shown here.
答案 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();