Search code examples
node.jsuuidjsonschema

How to check UUID using regular expressions?


In order to make validation over a api, i'm send companyId as UUID like: 71158c1a-56fd-4dd4-8e7f-fb95711a41de

To have this validation I used jsonschema with the following patterns (test all 3 of them):

  • /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$
  • /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi
  • [\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}

jsonschema:

  companyId: {
      type: "string",
      default: "",
      title: "The companyId Schema",
      pattern: "/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$",
      examples: ["71158c1a-56fd-4dd4-8e7f-fb95711a41de"],
    },

For some reason the validation returned me errors:

    path: Ä 'companyId' Å,
    property: 'instance.companyId',
    message: 'does not match pattern "/ÜÄ0-9a-fA-FÅä8åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä12å$"',
    schema: ä
      type: 'string',
      default: '',
      title: 'The companyId Schema',
      pattern: '/ÜÄ0-9a-fA-FÅä8åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä12å$',
      examples: ÄArrayÅ
    å,
    instance: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
    name: 'pattern',
    argument: '/ÜÄ0-9a-fA-FÅä8åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä4åÖb-Ä0-9a-fA-FÅä12å$',
    stack: 'instance.companyId does not match pattern "/ÜÄ0-9a-fA-FÅä8åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä4åÖÖb-Ä0-9a-fA-FÅä12å$"'
  å,

Also im getting these cyrillic letters, maybe this is the reason?


Solution

  • The latest version of JSON Schema supports the uuid format (you may need to explicitly turn on format validation in the implementation, as by default it is supposed to be annotation-only):

    {
      "$schema": "https://json-schema.org/draft/2020-12/schema",
      "type": "string",
      "format": "uuid",
    }
    

    Also, you have a stray / in your pattern before the ^ anchor, so your pattern will never match.