-1

I try to define a regex in Javascript who can accept separators like spaces, points, double-points and dashes. My regex is working when there is no separators but when I add space or other separator, it's not working.

I have to precise: this regex is for French phone number (0123456789 or 01.23.45.56.78 or 01 23 45 67 89,...). Also, this regex can accept "+33" who replaces the first "0".

This is my regex

var regex = /^(0|\+33)[1-9]([-.: ]?[0-9]{2}){4}$/;

Can someone tell me what is wrong?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

3 Answers3

1

Thank you everyone for yours quick answers!

So as Wiktor Stribiżew said, my regex was good! (Thank you for the link, I didn't know this website).

I have tried a lot of things so sorry for the late reply, but I have found where was my error!

My function is the next one (called by a onblur):

function verifTel(champ) {
     var regex = /^(0|\+33)[1-9]([-.: ]?[0-9]{2}){4}$/;
     if(!regex.test(champ.value)) {
         surligne(champ, true);
         return false;
     } else {
         surligne(champ, false);
         return true;
     }
 }

surligne() is my function for changing the color of the input text. When I wrote 0123456789 my text was green but when I wrote 01.23.45.67.89 my text was red.

BUT my error wasn't in JavaScript... My error was here, in my HTML:

<input id="tel" type="number" placeholder="Téléphone" required onblur="verifTel(this)">

The type="number" accept only numbers and "e" letter. So, I have changed the type to "text" and now it's working!

Thank you everyone for your answers! Have a nice day!

  • Are you sure this should be posted as an answer? You kept the code to yourself, did not show it to us, and thus could only answer your own question yourself. – Wiktor Stribiżew Dec 30 '16 at 11:30
  • Previously you ask for my code, so this is just my code which is usefull for this case.... So yes, this is my final code for this part. The real problem wasn't my regex as I expected but what else do you want? I haven't post my input before because I though my error was on the regex. – Nicolas Milliard Dec 30 '16 at 11:54
0

This works :

var regex = /^(0|(\+33[\s]?([0]?|[(0)]{3}?)))[1-9]([-. ]?[0-9]{2}){4}$/;

Explanation is available here

Silloky
  • 147
  • 13
-1

Just add * after [-.: ]. With this change you'll support multiple spaces between the parts.

var regex = ^(0|\+33)[1-9]([-.: ]*?[0-9]{2}){4}$;
Tome Pejoski
  • 1,582
  • 2
  • 10
  • 34