regex手机验证不起作用-javascript

regex on phone verification not working - javascript

本文关键字:-javascript 不起作用 验证 手机 regex      更新时间:2023-09-26

不确定为什么我的regex验证不起作用。。。如果我输入了一个数字,它仍然表示这是一个无效的数字。。。为什么?我试图检查无效的数字,但如果我键入一个数字,我也会收到一个错误。

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>

此正则表达式将完成格式(###)###-#### 的输入工作

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

但总的来说,将用户限制为这种非常特定的格式并不是一个好主意。我建议你接受多个版本的电话号码,当然只包括没有括号或连字符等其他字符的号码。