插入布尔函数以使用 'Yup' 库进行验证

Inserting a Boolean function to validate with 'Yup' library

我的这个函数运行正常,return是一个布尔值。我想插入此函数以验证 'Yup' 库中的输入字段。

函数如下: 这个功能。运行成功。

  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
  }

这里是我想在'Yup'实现的地方: 这是行不通的。它不 return 验证消息。

async function validateProduct() {
    try {
      const schema = Yup.object().shape({     
        hsCode: Yup.number()
          .test(isHsCodeAllowed, 'This code is prohibited') // <---------------    
      });
}    

您可以使用任何可行的方法或其他解决方案。不强制使用'test'方法,但必须使用Yup库。

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';
}