我的这个函数可以正常工作并返回一个布尔值。我想插入此函数来验证“是”库中的输入字段。
功能如下: 这个功能。它工作成功。
console.log(isHsCodeAllowed(111111)) //true
console.log(isHsCodeAllowed(222222)) //false
function isHsCodeAllowed(hsCode) {
let status = ''
const hsCodeList =
[
{ "number": 111111, "status": "allowed" },
{ "number": 222222, "status": "prohibited" },
{ "number": 333333, "status": "allowed" },
{ "number": 444444, "status": "prohibited" }
]
for (let i = 0; i < hsCodeList.length; i++) {
if (hsCode === hsCodeList[i]["number"]) {
status = hsCodeList[i]["status"]
}
}
return status === 'allowed' || false
}
这是我想在“是的”中实现它的地方: 这没用。它不会返回验证消息。
async function validateProduct() {
try {
const schema = Yup.object().shape({
hsCode: Yup.number()
.test(isHsCodeAllowed, 'This code is prohibited') // <---------------
});
}
您可以使用任何有效的方法或其他解决方案。不强制使用'test'方法,但必须使用Yup库。
答案 0 :(得分:2)
https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema
.test
函数在开头接受两个字符串参数,然后是验证器函数。
const schema = Yup.object().shape({
hsCode: Yup
.number()
.test('is-allowed-HsCode', 'This code is prohibited', isHsCodeAllowed)
});
也在你的验证器函数中抛出一个 ValidationError :
function isHsCodeAllowed(hsCode) {
const hsCodeList = [
{ "number": 111111, "status": "allowed" },
{ "number": 222222, "status": "prohibited" },
{ "number": 333333, "status": "allowed" },
{ "number": 444444, "status": "prohibited" }
];
const status = hsCodeList.find(c => c.number === hsCode)?.status;
return status === 'allowed';
}