Search code examples
javascriptvalidationjoi

How to custom validation in Joi?


I am using Joi library to validate data but I have a problem with custom() validation in schema, the following code below I use custom() method to convert desc to -1 and asc to 1 but I always get the result desc or esc after excuted. How can I convert it to get my desired result ?

   const mySchema = {
      my_obj: Joi.object().keys({
        id: Joi.number().positive().required(),
        sort: Joi.string()
            .lowercase()
            .valid('desc', 'asc')
            .default('desc')
            .custom((value, helpers) => {
                switch (value) {
                    case 'desc':
                        return -1;
                    case 'asc':
                        return 1;                 
                }
            }),
      })
   }

  const obj = {
     my_obj: {
       id: 1,
       sort: 'desc'
     }
  }

  const { value, error } = Joi.compile(mySchema)
        .prefs({ errors: { label: 'key' }, abortEarly: false })
        .validate(obj);

  console.log(value); // output similar to `obj` variable
  // the output of `sort` field should be return -1 | 1 but always getting desc | asc

My desired output:

{
   my_obj: {
      id: 1,
      sort: -1
   }
}

Solution

  • It will work after removing .valid('desc', 'asc'), if the .valid() rule passes, the .custom() rule will not be applied.

    Joi.object().keys({
      id: Joi.number().positive().required(),
      sort: Joi.string()
      .lowercase()
      .default('desc')
      .custom((value, helpers) => {
        switch (value) {
          case 'desc':
            return -1;
          case 'asc':
            return 1; 
        }
      }),
    })
    

    Date to validate:

    {
      id: 1,
      sort: 'desc'
    }
    

    Validated object:

    {
      "id": 1,
      "sort": -1
    }