Yup: How to use a dynamic variable in a static yup schema?

Created on 10 Oct 2018  路  3Comments  路  Source: jquense/yup

I want to statically create a yup schema (the schema is defined once) that takes a dynamic variable each time it's called (the variable can be different with each call). Is this possible?

e.g.,

// 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:
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

(I realize it's possible to dynamically create a schema each time with a variable in that scope. However, I'm working in a codebase with many statically-defined yup schemas, with a function mapping the schemas to their corresponding fields. I'm hoping for a way to be able to be able to use dynamic variables for just a couple of those schemas that need them, and not have to modify every static schema to be dynamic.)

Most helpful comment

That works, thank you! 馃憤

For future readers, here's the code that includes passing the context into validateSync():

// file: schema.js
// create the schema once
yup = require('yup');
const schema = yup.mixed().test(
  'my-test-name',
  'cannot be an existing value',
  function test(value) {
    return !this.options.context.myArray.includes(value)
  } 
);
module.exports = schema;


// other file:
schema = require('./schema.js');
let myArray = ['blue', 'green'];
schema.validateSync('yellow', { context: { myArray: myArray });

All 3 comments

Hi! Seems like all you need there, is provide context during call validate or validateSync.
https://github.com/jquense/yup#mixedvalidatevalue-any-options-object-promiseany-validationerror

yes context as an option les you pass in arbitrary data and reference it from tests, either via ref()s or in the test function

const schema = yup.mixed().test(
  'my-test-name',
  'cannot be an existing value',
  function test(value) {
    return !this.options.context.myArray.includes(value)  
);

That works, thank you! 馃憤

For future readers, here's the code that includes passing the context into validateSync():

// file: schema.js
// create the schema once
yup = require('yup');
const schema = yup.mixed().test(
  'my-test-name',
  'cannot be an existing value',
  function test(value) {
    return !this.options.context.myArray.includes(value)
  } 
);
module.exports = schema;


// other file:
schema = require('./schema.js');
let myArray = ['blue', 'green'];
schema.validateSync('yellow', { context: { myArray: myArray });

Was this page helpful?
0 / 5 - 0 ratings