Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Bravo Avatar asked Nov 15 '15 12:11

Bravo


1 Answers

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.

like image 169
Ford Avatar answered Sep 28 '22 03:09

Ford