Rafael Maiolla
Rafael Maiolla

Reputation: 383

Stripping unknown keys when validating with Joi

I'm using Joi to validate a JavaScript object in the server. The schema is like the following:

var schema = Joi.object().keys({
    displayName: Joi.string().required(),
    email: Joi.string().email(),
    enabled: Joi.boolean().default(false, "Default as disabled")
}).unknown(false);

The schema above will report an error if there is an unknown key in the object, which is expected, but what I want is to strip all the unknown silently, without an error. Is it possible to be done?

Upvotes: 16

Views: 18573

Answers (4)

Jayant Malik
Jayant Malik

Reputation: 1548

As in Version 14.3.4, there is a simple solution to this issue. Here is the code that solves the problem for you.

// Sample data for testing.
const user = {
    fullname: "jayant malik",
    email: "[email protected]",
    password: "password111",
    username: "hello",
    name: "Hello"
};

// You define your schema here
const user_schema = joi
  .object({
    fullname: joi.string().min(4).max(30).trim(),
    email: joi.string().email().required().min(10).max(50).trim(),
    password: joi.string().min(6).max(20),
    username: joi.string().min(5).max(20).alphanum().trim()
  })
  .options({ stripUnknown: true });

// You validate the object here.
const result = user_schema.validate(user);

// Here is your final result with unknown keys trimmed from object.
console.log("Object with trimmed keys: ", result.value);

Upvotes: 9

Steve
Steve

Reputation: 4985

Here is the current way to include the strip unknown option:

const validated = customSchema.validate(objForValidation, { stripUnknown: true });

If you pass in an objForValidation that has a key which isn't defined in your customSchema, it will remove that entry before validating.

Upvotes: 5

Doug Wilhelm
Doug Wilhelm

Reputation: 796

const joi = require('joi');

joi.validate(object, schema, {stripUnknown:true}, callback);

Upvotes: 4

Jerome WAGNER
Jerome WAGNER

Reputation: 22422

You need to use the stripUnknown option if you want to strip the unknown keys from the objects that you are validating.

cf options on https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback

Upvotes: 14

Related Questions