Bravo
Bravo

Reputation: 1139

Joi validation schema - two fields must not have the same value

Assume I have the following schema:

var schema = {
  fieldOne: Joi.string().required(),
  fieldTwo: Joi.string().required()
};

Is it possible to set a validation rule that checks if both fields have different values?

Upvotes: 17

Views: 10734

Answers (1)

Ford
Ford

Reputation: 2597

Yes it is. You do this by making use of Joi.ref and Joi.invalid (aliased to Joi.disallow). For your particular example, it would be:

var assert = require('assert');
var Joi = require('joi');

var schema = Joi.object().keys({
  fieldOne: Joi.string().required(),
  fieldTwo: Joi.string().disallow(Joi.ref('fieldOne')).required()
});

And testing it yields us what we would expect:

assert.ok(Joi.validate(4, schema).error !== null);
assert.ok(Joi.validate({ fieldOne: 'a', fieldTwo: 'a' }, schema).error !== null);
assert.ok(Joi.validate({ fieldOne: 'a', fieldTwo: 'b' }, schema).error === null);

It works by referencing fieldOne in our definition of fieldTwo and disallowing the same value.

Upvotes: 41

Related Questions