简体   繁体   中英

How To Make Joi Warning On Non-Existant property

How can I use Joi to throw a WARNING but not an ERROR if a particular element does not exist?

My Code:

const Joi = require('joi');

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required(),
    birth_year: Joi
        .number()
        .min(2000)
        .warn()
});

console.log({ error, warning, value } = schema.validate({ username: 'abc', birth_year: 1994 }));
console.log({ error, warning, value } = schema.validate({ username: 'abc'}));

I can successfully see a warning when the birth year does not have the minimum I require

'"birth_year" must be greater than or equal to 2000'

however, I also want to WARN if birth year does not exist.

Currently I do not get a warning or an error. If I add .required() to the birth year schema it will ERROR if birth year does not exist. I have tried making this:

birth_year: Joi
        .number()
        .min(2000)
        .warn()
        .required()
        .warn()

however this generates a runtime error because.warn() terminates the schema options. I also tried moving.required to be the second option, but again it errors, not warns.

Use warn() and validateAsync() method with warnings option to true:

const schema = Joi.object({
          username: Joi.string()
                    .alphanum()
                    .min(3)
                    .max(30)
                    .required(),
          birth_year: Joi
                      .number()
                      .min(2000)
                      .warn()     // warning
                      .required()
});

Now you can validate it with validateAsync() method in async function like this:

(async function(){
    try {
       const { value, warning } = await schema.validateAsync({ username: 'abc', birth_year: 1994 }, { warnings: true });
    } catch(e) {
       console.log(e);
    }
})();

This code will throw error if birth_year field does not exist or warning if birth_year field exists but not as required.

Note that warn() will terminate the current ruleset and cannot be followed by another rule option. Use rule() to apply multiple rule options.

For more information: https://joi.dev/api/?v=17.7.0#anywarn

Here's one way to do it, if you are adamant about issuing a warning, instead of an error: https://stackblitz.com/edit/node-nuys5f?file=index.js

Essentially you would create another variable which would validate the variable you want to issue a warning for when it is not present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM