0

I have a regex that validates UAE numbers like: 00971585045336 here is the regex: /00971(?:50|51|52|53|54|55|56|57|58|59|2|3|4|6|7|9)\d{7}$/

I have a requirement to add support for toll free numbers like: 0097180038249953 or 0097180022988

I am not good with regex so I need help to make it possible. Thanks in advance.

Syed Fasih
  • 302
  • 4
  • 12

1 Answers1

4

You can use the following regex, assuming the tool free number format is 00971800, followed by 5 or 8 digits. Your original regex is simplified with character classes. The test shows 4 valid numbers, followed by invalid numbers:

const regex = /^00971((5\d|[234679])\d{7}|800(\d{5}|\d{8}))$/;
[
  '00971581234567',
  '0097171234567',
  '0097180012345',
  '0097180012345678',
  '0097158123456',
  '009715812345678',
  '009717123456',
  '00971712345678',
  '00971800123456',
  '009718001234567',
].forEach((str) => {
  let valid = regex.test(str);
  console.log(str + ' ==> ' + valid);
});

Output:

00971581234567 ==> true
0097171234567 ==> true
0097180012345 ==> true
0097180012345678 ==> true
0097158123456 ==> false
009715812345678 ==> false
009717123456 ==> false
00971712345678 ==> false
00971800123456 ==> false
009718001234567 ==> false

Explanation:

  • ^ - start of string
  • 00971 - expect literal text
  • ( - start group, used for logical OR
    • ( - start group, used for logical OR
      • 5\d - expect a 5, followed by a digit
      • | - OR
      • [234679] - character class with a single char of allowed digits
    • ) - end of group
    • \d{7} - 7 digits
    • | - OR
    • 800 - literal text
    • ( - start group, used for logical OR
      • \d{5} - 5 digits
      • | - OR
      • \d{8} - 8 digits
    • ) - end of group
  • ) - end of group
  • $ - end of string
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20