javascriptjoi

Validate Comma Separated String by JOI


I am implementing JOI validation and want to validate comma separated string by JOI. This string contain only particular text string like 'admin','client', 'customer', 'user'. For example check below. I can validate this by JavaScript, but i want to validate by JOI

function checkString(perm)
{
    const a = ['admin','client', 'customer', 'user'];
     
    const check = perm.split(",");
     
    if(!check.every(val => a.includes(val)))
    {
            return false;
      }
     
      return true;
}
        
//alert(checkString('admin,client,customer'))            //true
//alert(checkString('customer'))                         //true
//alert(checkString('admin,client,buyer'))               //false
//alert(checkString('buyer'))                            //false
//alert(checkString('admin,client,customer,buyer'))      //false


Solution

  • Looking at the documentation and this question: How to add custom validator function in Joi?

    I would try string.custom

    const schema = Joi.string().custom((value, helpers) => {
      const values = value.split(','); 
      const invalidValues = values.filter(v => !allowedValues.includes(v)); 
      if (invalidValues.length > 0) {
        return helpers.message(`The string contains invalid values: ${invalidValues.join(', ')}`);
      }
      return value; // Validation passed
    }, 'Custom comma-separated validation');