我想静态创建一个 yup 模式(模式定义一次),每次调用时都会使用一个动态变量(每次调用的变量可能不同)。这可能吗?
例如,
// file: schema.js
// create the schema once
yup = require('yup');
const schema = yup.mixed().test(
'my-test-name',
'cannot be an existing value',
value => !myArray.includes(value) // How to reference myArray here?
// As written, it results in "ReferenceError: myArray is not defined"
);
module.exports = schema;
// other file that imports the schema:
schema = require('./schema.js');
let myArray = ['blue', 'green'];
schema.validateSync('yellow'); // should pass validation, because 'yellow' not in myArray
myArray = ['orange', 'yellow'];
schema.validateSync('yellow'); // should fail validation, because 'yellow' is in myArray
(我意识到每次都可以使用该范围内的变量动态创建模式。但是,我正在使用许多静态定义的 yup 模式的代码库中工作,并使用函数将模式映射到其相应的字段。我是希望有一种方法能够将动态变量仅用于几个需要它们的模式,而不必将每个静态模式都修改为动态的。)