Skip to content

Instantly share code, notes, and snippets.

@todgru
Created March 18, 2021 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todgru/af23eb14a46fd9d0ee08436c163f1c79 to your computer and use it in GitHub Desktop.
Save todgru/af23eb14a46fd9d0ee08436c163f1c79 to your computer and use it in GitHub Desktop.
always force a value for a field in a schema using Joi custom validator

Joi Custom Validtion

Adds a custom validation function to execute arbitrary code

https://joi.dev/api/?v=17.4.0#anycustommethod-description

Set a null value for any data type regardless of whats given. I used this in a nested if/when statement to only trigger under certain conditions based on other key values.

Here's the gist:

const forceNullValue = (value, helpers) => {
    // we could do all sorts of cool stuff in here, like inspect `value`, returning
    // whatever custom values we want. See example in Joi documentation.
    return null
};

const schema = Joi.any().custom(forceNullValue, "ignore input and force null value validation");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment