-1

I'm trying to validate the following phone number with regex:

1) +415XXXXXXXX
2) 00415XXXXXXXX
3) 41 5XXXXXXXX
4) 41 05XXXXXXXX
5) 05XXXXXXXX
6) 5XXXXXXXX

I tries this expression

^\+?41?\s?0?5\d{8}$

and was able to validate situations (1,3,4), could any one help me to adjust the above one to be able to cover the rest scenarios?

RAZ
  • 61
  • 8
  • 2
    Your regex seems to only validate phone numbers that begin with "41", which explains why 1, 3, 4 are the only ones that match. I'm not sure what the conditions of your problem are, since you can technically write a regex to accept any string of numbers as "phone numbers". – General Poxter Oct 28 '20 at 15:40
  • 2
    Use `^(?:(?:\+|00)415|41 0?5|0?5)\d{8}$` ([demo](https://regex101.com/r/IDkscC/2)) – Wiktor Stribiżew Oct 28 '20 at 15:40
  • that was great, thanks, i didn't know what to use to make the number start with 0041 or +41 :) – RAZ Oct 28 '20 at 15:52

1 Answers1

0

One "brute force" approach would be to just handle each prefix separately in an alternation:

var nums = ["+41512345678", "0041512345678", "41 512345678", "41 0512345678", "0512345678", "512345678", "2128675309"];
nums.forEach(function(number) {
    console.log(number + " passes? " +
/^(?:\+415|00415|41 0?5|0?5)\d{8}$/.test(number));
});
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360