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)?