hapijs / joi

The most powerful data validation library for JS
Other
20.88k stars 1.51k forks source link

How to validate a number is even? #2634

Open jeffski opened 3 years ago

jeffski commented 3 years ago

Support plan

Context

How can we help?

I have a use case that requires numeric values to be even. Values are entered via an API request, so I can not use the UI to enforce the numbers. Is there any feature within Joi that would allow me to validate a number is even?

Adibla commented 3 years ago

You can obtain this using custom validation https://github.com/sideway/joi/blob/master/API.md#anycustommethod-description

A simple implementation could be

const Joi = require('joi');

const evenValidation = (value, helpers) => {
    if(value % 2){
        throw new Error('is odd');
    }
    return value;
};

const schema = Joi.number().custom(evenValidation, 'even validation')

schema.validate(30) // valid

schema.validate(29)
/*
{
  value: 29,
  error: [Error [ValidationError]: "value" failed custom validation because is odd] {
    _original: 29,
    details: [ [Object] ]
  }
}
*/