Search code examples
javascriptangularregextypescript

Regular Expression to validate a CAGE Code


We need to write a RegEx which can validate a CAGE Code

A CAGE Code is a five (5) position code. The format of the code is

  • the first and fifth position must be numeric.
  • The second, third and fourth may be any mixture of alpha/numeric excluding alpha letters I and O.
  • Case insensitive

We came up with a RegEx cageCode = new RegEx(/^[a-zA-Z0-9]{5}$/) which is not properly validating the requirements given.

What could be the possible regEx which could validate the requirements mentioned?


Solution

  • You're trying to match 5 characters which could be either numbers or letters. Try something like this:

    ^\d(?:(?![ioIO])[A-Za-z\d]){3}\d$
    

    To break it down:

    1. ^\d: Will check if the string starts with a number
    2. (?:(?![ioIO])[A-Za-z\d]){3}: To check if there are 3 alphanumeric characters except i/o/I/O
    3. \d$: To validate if the string ends with a number