Search code examples
hapi.jsjoi

why is this joi regex validation for hex color failing


Why is this regex should match but it's failing?

error

child "color" fails because ["color" with value "#333acf " fails to match the required pattern: /^#[A-Fa-f0-9]{6}$/]

  validate: {
        payload:{
            avatar: joi.object().keys({
              color: joi.string().regex(/^#[A-Fa-f0-9]{6}$/),
              icon: joi.string().min(2)
          })
        }
    }

payload

{
    "avatar": {color:"#333acf ",icon:"b1"}
}

Solution

  • Your color string has an extra space at the end. Should be

    {
        "avatar": {color:"#333acf",icon:"b1"}
    }
    

    or your regex needs to allow strings longer than 6 characters by removing the end of string anchor.

    /^#[A-Fa-f0-9]{6}/