Joi: Validate subset of values

Created on 29 Jul 2015  路  7Comments  路  Source: sideway/joi

Is there a way to supress errors for any keys not present in the values object? For example:

const testSchema = Joi.object().keys({
  foo: Joi.string().required(),
  bar: Joi.string().required()
});

 Joi.validate({foo:'test'}, testSchema);

In the above example, I need to make it so that bar is not tested or throwing errors when it is not passed in as a value.

I understand you could create single schemas for each key, but my schema is quite large and I will require a full validation later on in the app.

Is there perhaps a way to pull out a single key's validator from the schema?

support

All 7 comments

This sounds like you want optional() instead of required(), no?

@nlindley no, bar is required, but only when I pass it in as part of the values object e.g.

 Joi.validate({foo:'test', bar:null}, testSchema);
// error, bar is required

The use case is for a web form, and I want to validate each fields input on change. Once the form is complete, I then want to do a final form validation with all of the values as per usual.

It looks like something similar was brought up in #556. You might see if optionalKeys() is helpful.

It'll get hairy if you have arrays, but yeah this solution works.

Hmm, this would mean an awful lot of optionalKeys declarations - I'd need one for each field in the form.

@Marsup is there any way of retrieving a key's rule from the Joi internals?

@jptaylor Are you using an object map which has dynamic values? We do a lot of that and use object.pattern(regex, schema)

So for your example you might have:

const testSchema = Joi.object().pattern(/.*/, Joi.string().required());

 Joi.validate({foo:'test'}, testSchema);

Unless I misunderstood your process, I don't think you're going for a good design.

In a form you either want to fully validate it before submit, or you want to validate a field on focus change (and that's not very wise to validate the whole form for just one field), in both cases, you'd need the required to be set to throw an error when a field should be set.

If you insist on keeping it that way for whatever reason, set the abortEarly to false and just ignore the required errors.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kailashyogeshwar85 picture kailashyogeshwar85  路  4Comments

alekbarszczewski picture alekbarszczewski  路  3Comments

Taxi4you picture Taxi4you  路  3Comments

longweiquan picture longweiquan  路  3Comments

normancarcamo picture normancarcamo  路  3Comments