Lucky500
Lucky500

Reputation: 507

regex on phone verification not working - javascript

not sure why my regex validation is not working... if I enter a number, it still says that it is an invalid number...why? I am trying to check for invalid numbers, but if I type a number I am getting an error as well.

function validatePhone() {

  var phone = document.getElementById("phone1").value;
  if (phone.length === 0) {
    console.log("phone number is required.");
    producePrompt("Phone number is required.", "messagePrompt", "red");
    return false;
  }

  if (!phone.match(/^[0-9]{10}$/)) {
    producePrompt("Please enter a valid Phone number.", "messagePrompt", "red");
    return false;
  }
  producePrompt("valid Number", "messagePrompt", "green");
  return true;
}

function producePrompt(message, promptLocation, color) {
  document.getElementById(promptLocation).innerHTML = message;
  document.getElementById(promptLocation).style.color = color;
}

function remove_msg() {
  producePrompt(" ", "messagePrompt", "red");
}
<form>
  <p>Please enter your phone number below:</p>
  <input type="tel" name="phone1" id="phone1" placeholder="(000)000-0000" onkeyup="validatePhone()" />
  <label for="" id="messagePrompt"></label>
  <br>
  <input type="button" value="send message" onclick="validatePhone()" />
</form>

Upvotes: 0

Views: 36

Answers (1)

ilyankou
ilyankou

Reputation: 1329

This regular expression will do the work for the input of format (###)###-####

 ^\([0-9]{3}\)[0-9]{3}\-[0-9]{4}$

But in general this is not a good idea to restrict users to this very specific format. I suggest you accept multiple versions of the phone number, definitely including only numbers with no other characters such as brackets or hyphens.

Upvotes: 1

Related Questions