Make sure a string does not start with a certain character using regular expression

Hello,

I am working on the validator program for phone numbers and have a question about checking if a string does not start with a dash or space

function telephoneCheck(str) {
  let regex = /^([1](\s|[-])?)?(\([0-9]{3}\)|(\s|[-])?[0-9]{3})/g
  console.log(regex.test(str));
  console.log(str.match(regex))
}

telephoneCheck("1123-456-7890")

My regex is only checking the first set of numbers and area code for now.

It works the following way:

Starts with optional area code that can be followed by a optional space.
^([1](\s|[-])?)?

Can either be parenthesis number (555) or a optional space/ dash with just three numbers as in 555
(\([0-9]{3}\)|(\s|[-])?[0-9]{3})

The issue is that the second term Makes the dash or space optional:
(\s|[-])?[0-9]{3})

This results in the input listed above passing despite not having a space between the area code and first set of numbers

true
[ '1123' ]

It also allows the number to start with a dash or space:
telephoneCheck("-123-456-7890") // ['-123']

Now I can edit the second half of the regex to require a gap between the area code and first set of numbers:

(\([0-9]{3}\)|(\s|[-])[0-9]{3})

But this creates a issue with the test now failing if the number does not start with a dash or space, such as in 123-456-7890. However, it does now fail if no gap is present between the area code and first set of numbers.

All of this boils down to the question of: How do I got about fixing this?

How can I make sure that the number does not start with a dash or space while still allowing for the optional area code that must have a dash or space following it (for non-parenthesis number)?

There are of course many different ways to solve this, but I did it by creating two patterns, one without parentheses and one with. Something like

str.match( without or with )

For without:

To allow 1 and space, I used the count designation {0,1} and this happens at the beginning
so the start of pattern is

/^(1\s){0,1}

and ends with

\d{4}$

You could use the same designation {0,1} to match either a hyphen or space like [- ]

For with:

The idea is very similar to without. You basically add \( and \) to match the parentheses.

And don’t forget to use regex101.com for testing.

1 Like

I decided to use a series of or statements to separate checking for a area code and no area code.

starts with 1-555 or 1(555)

or

starts with 555 or (555)

Basically a or statement nested within another or statement. Would post my final regex, but don’t want to spoil it for others who haven’t done it.

Then this was followed by the \d{4}$ you mentioned before.

Thank you a lot!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.