joi validation schema : value could be of several length possibles

448 Views Asked by At

I am using joi in a node project, and I would like to put the following rule : my field could be of length 6 or 8 (nothing else), I've tried to do the following but its not working :

Joi.object({
    iban: Joi.string().alphanum().length(6).length(8)
  })

The last written rules override the first one, so here I only accept value with length 8 and no more value with length 6

Thanks in advance

2

There are 2 best solutions below

0
On

Try writing custom validator like this. you can read more about custom validators here

Joi.object({
    iban: Joi.string().alphanum().custom((value, helper) => {
       if(value.length === 6 || value.length === 8){
           return value;
       } else {
           return helper.message("iban must be 6 or 8 characters long")
       }
    });
})
``
0
On

this one is working well :

Joi.alternatives().try(Joi.string().alphanum().length(6), Joi.string().alphanum().length(8))