Need help with Telephone number validator How to use if...then in RegEx like if one is true another must be true

I am failing the if this bracket: ‘(’ exists then ‘)’ should also exists.
Is there a way to use if…then in regEx.

I can forcefully pass the test here by creating another reg ex that counts the number of brackets and if its less than one then return false but I think that would be sort of cheating.

I also want to ask if in the current code, do you find anything forcefully making correct or not

  **Your code so far**

function telephoneCheck(str) {
let newStr=str.split("");
newStr=newStr.filter(a=>/\d/.test(a));
let regEx=/^(?!-)1*\s*?\(?\d{3}\)?-?\s?\d{3}\s?-?\d{4}(?!(\))$)/;
if (regEx.test(str) && (newStr.length===10 || (newStr.length===11) && newStr[0]==='1')){return true;}

return false;
}

console.log(telephoneCheck("-1 (757) 622-7382"));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 OPR/76.0.4017.177

Challenge: Telephone Number Validator

Link to the challenge:

You can use | (=or) for that, although it doesn’t quite work the way you want

A good example is a regex for string literals: "bla" and 'bla' are valid, but not "bla' and 'bla". The regex for that could look like this: /("\w*"|'\w*')/

1 Like

I passed it using a simple OR statement, I don’t know why I didn’t think of it. Didn’t thought seriously of your comment when you said it doesn’t quite work the way you want but later it was OR that ended up solving the problem :slightly_smiling_face:

(\(\d{3}\)|\d{3})

If there is bracket then there should be three digits then another brackets. If there is no brackets then there should just be three digits.

1 Like

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