skip to Main Content
const resultsDiv = document.getElementById('results');
const value = '2555-555-5555';
const regex = /(1s?)?(d{3}|(d{3}))[-s]?d{3}[-s]?d{4}/; //I found this is an incorrect regex

if (regex.test(value)) {
  console.log(regex.test(value)); //is false
  resultsDiv.querySelector("p").textContent = `Valid US number: ${value}`;
} else {
  resultsDiv.querySelector("p").textContent = `Invalid US number: ${value}`;
}
<div id="results"><p></p></div>

The if condition here should not be executing.

2

Answers


  1. i have looked to your example, modify some things statically and the result is fine

    const value = "123465789";
    const regex = /(1s?)?(d{3}|(d{3}))[-s]?d{3}[-s]?d{4}/g;
    
    if (!value) {
        alert("Please provide a phone number");
    }
    
    if (regex.test(value)) {
        console.log(regex.test(value));
        console.log("if")
    } else {
        console.log("else")
        console.log(regex.test(value))
    }

    the result is :
    else
    false

    Login or Signup to reply.
  2. Can you try like this

    Valid

    const value = "(555) 555-1234";
    const regex = /(1s?)?(d{3}|(d{3}))[-s]?d{3}[-s]?d{4}/g;
    
    if (!value) {
      alert("Please provide a phone number");
    }
    
    if (value.match(regex)) {
      console.log(value.match(regex));
      console.log(`Valid US number: ${value}`);
    } else {
      console.log(`Invalid US number: ${value}`);
    }
    

    Console: [‘(555) 555-1234’]

    Valid US number: (555) 555-1234

    Invalid Phone

    const value = "99999";
    const regex = /(1s?)?(d{3}|(d{3}))[-s]?d{3}[-s]?d{4}/g;
    
    if (!value) {
      alert("Please provide a phone number");
    }
    
    if (value.match(regex)) {
      console.log(value.match(regex));
      console.log(`Valid US number: ${value}`);
    } else {
      console.log(`Invalid US number: ${value}`);
    }
    

    Invalid US number: 99999

    Use match https://www.w3schools.com/jsref/jsref_match.asp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search