Johnston
Johnston

Reputation: 20884

Reject phone number with all same digits in javascript?

I am looking to reject phone numbers that have all the same digits.

Example: 222-222-2222 or 333-333-3333

I tried stupidly looping through all the characters, but that was a bad idea.

Upvotes: 2

Views: 3006

Answers (5)

erosman
erosman

Reputation: 7721

If you want to match the exact pattern

var str = '222-222-2222';
allowed(str); // false, console log bad

var str = '123-456-7890';
allowed(str); // true, console log good

function allowed(n) {

  if (/(\d)\1{2}-\1{3}-\1{4}/.test(n)) { console.log('bad'); return false; }
  console.log('good');
  return true;
} 

Here is the fiddle

Good luck :)

Upvotes: 2

anubhava
anubhava

Reputation: 785296

You can use this regex:

^(?!(\d)\1+(?:-\1+){2}$)\d+(-\d+){2}$

Online Demo

Upvotes: 4

elixenide
elixenide

Reputation: 44841

You can do this:

function AllSameDigits(str) {
    return /^(\d)\1+$/.test(str.replace(/[^\d]/g,''));
}

str='222-222-2222';
alert(AllSameDigits(str));

This strips out all non-digit characters, then asks: does the string start with a digit and consist of only the same digit repeated some number of times?

Upvotes: 1

ruakh
ruakh

Reputation: 183381

To test if a string contains only one distinct digit character (plus potentially arbitrary many non-digit characters), you can use:

function areAllDigitsTheSame(phoneNumber) {
    return /^\D*(\d)(?:\D*|\1)*$/.test(phoneNumber);
}

To test if a string matches the exact pattern ###-###-#### with all digits being the same, you can use:

function areAllDigitsTheSame(phoneNumber) {
    return /^(\d)\1\1-\1\1\1-\1\1\1\1$/.test(phoneNumber);
}

In both cases, the key point is that the () notation in a regex "captures" what it matches and makes it available for a back-reference (\1) to specify that it matches only an identical substring.

Upvotes: 4

aelor
aelor

Reputation: 11116

you need to first remove the hiphens and then check your number with this :

^(\d)\1+$

demo here : http://regex101.com/r/iJ2aB0

Upvotes: 0

Related Questions