Faisal Manzer
Faisal Manzer

Reputation: 2129

Raise validation when recive extra key in yup object

I am using yup for object validations. I have the following schema

const schema = yup.object().shape({
  name: yup.string().required(),
});

I am validating it with object

{
  "name": "Foo",
  "desc": "Lorem ipsum"
}

Yup validates this object although it has an extra key desc. I want to raise the error for extra keys in the object.

I have tried with abortEarly and stripUnknown in .validate but it doesn't work.

schema.validateSync(data, { strict: true, stripUnknown: true })

Upvotes: 1

Views: 2187

Answers (2)

Breno Gusson
Breno Gusson

Reputation: 1

Complementing our friend response:

noUnknown - Validate that the object value only contains keys specified in shape().

strict - Only validate the input, skipping type casting and transformation

stripUnknown - Remove unspecified keys from objects. When 'strict' is set to true, 'stripUnknown' will automatically be set to false.

So, to do it right you should add these 3 options to your validation:

{ abortEarly: false, strict: false, stripUnknown: false }

And therefore:

.noUnknown(true)

Example: Block extra keys (to exit with error) and transform Date.

export const updateCustomerValidation = validation((getSchema) => ({
    params: getSchema<IParamsUpdateClientes>(yup.object().shape({
        clid: yup.string().required()
    })),
    body: getSchema<IBodyUpdateClientes>(yup.object().shape({
        ...
        data_nascimento: yup.date().transform((value) => new Date(value))
    }).noUnknown(true)
    )
}));

Tip: Yup validate a date using Date() constructor, so you have to transform it before validating.

Yup has such a bad documentation, I hope they update it soon.

Upvotes: 0

Ycee_thetechie
Ycee_thetechie

Reputation: 31

You need to append the .strict() to the object you are validating. This makes the validation fail and then you can handle the error however you wish to do that.

So, in your case, change your schema to this:

  const schema = yup.object().shape({
    name: yup.string().required()
}).noUnknown(true).strict();


await schema.validate(data, { abortEarly: false });

Upvotes: 3

Related Questions