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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With