skip to Main Content

I have the below Joi validation for a field called store_type

store_type: Joi.string().valid(...Object.values(storeTypes))
 .error(() => ({
    message: `Store Type must be one of: ${Object.values(storeTypes).join(', ')}`,
 })).default(storeTypes.aaa),

wherein storeTypes is defined as

storeTypes: {
 aaa: 'AAA',
 bbb: 'BBB'
}

As per the above validation, what I expect is

  • When I don’t pass a value for store_type it should by default set the value as AAA
  • In case if I pass an empty string or non-empty string then it should check if thats either AAA or BBB, if not then it should fail with the mentioned error

What changes can be done to the above code so that it works as per my requirement.

Thanks in advance

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the answer @cmgchess Actually the below snippet worked for me

    store_type: Joi.string().allow('').valid(...Object.values(storeTypes))
              .default(storeTypes.aaa)
              .error(() => ({
                message: `Store Type must be one of: ${Object.values(storeTypes).join(', ')}`,
              }))
    

  2. error() must return an Error object

    • I tried myself and had to modify the error message with the custom error message that you want to add. you can also test it here
        store_type: Joi.string()
          .valid(...Object.values(storeTypes))
          .error((err) => {
            err[0].message = `Store Type must be one of: ${Object.values(storeTypes).join(', ')}`
            return err
          })
          .default(storeTypes.aaa)
    

    now you can access the error when you validate

    const { error, value } = schema.validate(inputObject)
    console.log(error.details[0].message)
    
    
    • or you can return an Error object
    store_type: Joi.string()
          .valid(...Object.values(storeTypes))
          .error(() => new Error(`Store Type must be one of: ${Object.values(storeTypes).join(', ')}`))
          .default(storeTypes.aaa)
    

    and access the error like

    const { error, value } = schema.validate(inputObject)
    console.log(error.message)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search