代码之家  ›  专栏  ›  技术社区  ›  Rob Bednark Bohdan

如何在静态yup模式中使用动态变量?

  •  0
  • Rob Bednark Bohdan  · 技术社区  · 6 年前

    我想静态地创建一个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模式,并使用一个函数将这些模式映射到它们相应的字段。我希望有一种方法能够将动态变量仅用于需要它们的一些模式,而不必将每个静态模式都修改为动态的。)

    2 回复  |  直到 6 年前
        1
  •  2
  •   Rob Bednark Bohdan    6 年前

    1. 使用第二个 Options 参数到 validateSync() context 钥匙
    2. 宣布 .test() 函数使用函数表达式,而不是箭头函数(因为yup将函数绑定到 this )
    3. this.options.context.variableName

    例如。,

    const yup = require('yup');
    
    // statically declare the schema
    const schema = yup.mixed().test(
      'my-test-name',
      'cannot be an existing value',  // error message
      function test(value) {
        // NOTE: this must not be an arrow function, because yup binds it to it's "this"
        // Note the use of this.options.context to reference the dynamic variable
        return !this.options.context.myArray.includes(value)  
      }
    );
    
    // Note the use of passing a { context: ... } as the second "options" parameter to validateSync()
    ret = schema.validateSync('yellow', { context: { myArray: ['blue', 'green'] } } );
    console.assert(ret === 'yellow');  // passes validation
    
        let errorMessage;
    try {
      schema.validateSync('blue', { context: { myArray: ['blue', 'green'] } } );
    }
    catch(error) {
      errorMessage = error.message;
    }
    console.assert(errorMessage === 'cannot be an existing value');
    
        2
  •  0
  •   Neverever    6 年前

    尝试导出创建动态架构的函数。请看下面。

    // file: schema.js
    // create the schema once
    yup = require('yup');
    
    // export as a function
    module.exports = myArray => {
      return yup.mixed().test(
        'my-test-name',
        'cannot be an existing value',
        value => !myArray.includes(value)  
      );
    };
    
    
    
    // other file that imports the schema:
    schema = require('./schema.js');
    let myArray = ['blue', 'green'];
    
    let blueGreenSchema = schema(myArray);
    blueGreenSchema.validateSync('yellow');  
    
    myArray = ['orange', 'yellow'];
    let orangeYellowSchema = schema(myArray);
    orangeYellowSchema.validateSync('yellow');