Javascript电话号码格式

Javascript Phone number Format

本文关键字:格式 电话号码 Javascript      更新时间:2023-09-26

看来我原来的问题已经解决了。我能够完成Pizza表单的大部分表单验证需求。但是现在我只是卡在电话号码验证和格式上。

我需要助手来验证我的电话号码。

电话号码必须是带有破折号的数字,例如222-222-2222,其他任何格式或空字段都应该在我点击提交按钮时引起警告,并且不允许提交表单,除非它是正确的

请查看我的代码document.PizzaForm.phone.value代码为我的披萨表单我不知道如何编辑代码来实现我的要求。

<html>
<head>
<title>Hello and JavaScript</title>
<script>
    function doClear()
    {
        document.PizzaForm.customer.value = "";
        document.PizzaForm.address.value = "";
        document.PizzaForm.city.value = "";
        document.PizzaForm.state.value = "";
        document.PizzaForm.zip.value = "";
        document.PizzaForm.phone.value = "";
        document.PizzaForm.email.value = "";
        document.PizzaForm.sizes[0].checked = false;
        document.PizzaForm.sizes[1].checked = false;
        document.PizzaForm.sizes[2].checked = false;
        document.PizzaForm.sizes[3].checked = false;
        document.PizzaForm.toppings[0].checked = false;
        document.PizzaForm.toppings[1].checked = false;
        document.PizzaForm.toppings[2].checked = false;
        document.PizzaForm.toppings[3].checked = false;
        document.PizzaForm.toppings[4].checked = false;
        document.PizzaForm.toppings[5].checked = false;
        document.PizzaForm.toppings[6].checked = false;
        document.PizzaForm.toppings[7].checked = false;
        document.PizzaForm.toppings[8].checked = false;
        return;
    }
    function doSubmit() 
    {
        if (validateText()==false)
        {
            alert("Required data missing in Step 1");
        }
        if (validateRadio()==false)
        {
            alert("Required data missing in Step 2");
        }
        if(validateTops()==false)
        {
            alert("Required data missing in Step 3");
        }

        var OrderWindow
        OrderWindow = window.open("","","status,height=500,width=500");
        OrderWindow.focus();
        with (OrderWindow.document)
        {
            write("<h1><center>Customer Order Summary</center></h1><p>")
            write("Name:" + document.PizzaForm.customer.value + "<br>")
            write("Address:" + document.PizzaForm.address.value + "<br>")
            write("City:" + document.PizzaForm.city.value + "<br>")
            write("State:" + document.PizzaForm.state.value + "<br>")
            write("Zip Code:" + document.PizzaForm.zip.value + "<br>")
            write("Phone Number:" + document.PizzaForm.phone.value + "<br>")
            write("E-Mail:" + document.PizzaForm.email.value + "<br>")
            write("Pizza Size:" + validateRadio() + "<br>")
            write("Pizza Toppings:" + validateTops() + "<br>")
            write("<h3><center>Thank You for your Order.</center></h3><p>")
        }
        return;
    }
    function validateText()
    {
        if (document.PizzaForm.customer.value == "")
        {
            alert("Please provide your name");
            document.PizzaForm.customer.focus();
        }
        if (document.PizzaForm.address.value == "")
        {
            alert("Please provide your address.");
            document.PizzaForm.address.focus();
        }
        if (document.PizzaForm.city.value == "")
        {
            alert("Please provide your City.");
        }
        if (document.PizzaForm.state.value == "")
        {
            alert("Please provide your State.");
        }
        if (document.PizzaForm.zip.value == "" ||
        isNaN( document.PizzaForm.zip.value ) ||
        document.PizzaForm.zip.value.length != 5 )
        {
            alert("Please provide your Zip code.");
            document.PizzaForm.zip.focus() ;
        }
        if (document.PizzaForm.phone.value == "" ||
        isNaN( document.PizzaForm.phone.value ) ||
        document.PizzaForm.phone.value.length != 10 )
        {
            alert("Please provide your phone number.");
            document.PizzaForm.phone.focus() ;   
        }
        var emailID = document.PizzaForm.email.value;
        atpos = emailID.indexOf("@");
        dotpos = emailID.lastIndexOf(".");
        if (atpos < 1 || ( dotpos - atpos < 2 ))
        {
            alert("Please enter correct Email.")
            document.myForm.Email.focus() ;
        }
        return (true);
    }
    function validateRadio() 
    { 
        if (document.PizzaForm.sizes[0].checked) true; 
        if (document.PizzaForm.sizes[1].checked) true; 
        if (document.PizzaForm.sizes[2].checked) true; 
        if (document.PizzaForm.sizes[3].checked) true; 
        return false; 
    }
    function validateTops()
    {
        var sizes = document.PizzaForm.toppings;
        var alert = ""
        if (PizzaForm.toppings[0].checked) alert = "Pepperoni, " + alert;
        if (PizzaForm.toppings[1].checked) alert = "Canadian Bacon, " + alert;
        if (PizzaForm.toppings[2].checked) alert = "Sausage, " + alert;
        if (PizzaForm.toppings[3].checked) alert = "Mushrooms, " + alert;
        if (PizzaForm.toppings[4].checked) alert = "Pineapple, " + alert;
        if (PizzaForm.toppings[5].checked) alert = "Black Olives, " + alert;
        if (PizzaForm.toppings[6].checked) alert = "Extra Cheese, " + alert;
        if (PizzaForm.toppings[7].checked) alert = "Plain, " + alert;
        return alert;
    }
</script>
</head> 
<body>
    <form Name ="PizzaForm">
        <h1> The JavaScrpt Pizza Parlor</h>
        <p>
        <h4> Step 1: Enter your name, address, phone number, and email:</h4>
        <font face="Courier New">
        Name: &nbsp;&nbsp;&nbsp;<Input name="customer" size="50" type="text"><br>
        Address:&nbsp;<Input name="address" size="50" type="text"><br>
        City: &nbsp;&nbsp;&nbsp;<Input name="city" size="15"type="text">
        State:<Input name="state" size="2"type="text"><br>
        Zip:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<Input name="zip" size="5"type="text">  <br>
        Phone: &nbsp;&nbsp;<Input name="phone" size="50"type="text"><br>
        Email: &nbsp;&nbsp;<Input name="email" size="31"type="text"><br>
        </ font>
        </ p>
        <p>
        <h4> Step 2: Select the size of pizza you want:</h4>
        <font face="Courier New">
        <input name="sizes" type="radio">Small
        <input name="sizes" type="radio">Medium
        <input name="sizes" type="radio">Large
        <input name="sizes" type="radio">Jumbo<br>
        </font>
        </ p>
        <p>
        <h4> Step 3: Select the pizza toppings you want:</h4>
        <font face="Courier New">
        <input name="toppings" type="checkbox">Pepperoni
        <input name="toppings" type="checkbox">Canadian Bacon
        <input name="toppings" type="checkbox">Sausage<br>
        <input name="toppings" type="checkbox">Mushrooms
        <input name="toppings" type="checkbox">Pineapple
        <input name="toppings" type="checkbox">Black Olives<br>
        <input name="toppings" type="checkbox">Green Peppers
        <input name="toppings" type="checkbox">Extra Cheese
        <input name="toppings" type="checkbox">Plain
        </ font>
        </ p>
        <input type="button" value="Submit Order" onClick="doSubmit()">
        <input type="button" value="Clear Entries" onClick="doClear()">
    </form>
</body>
</html>

电话号码必须是带破折号的数字,例如222-222-2222

你可以使用正则表达式来检查你的电话号码。这将精确匹配3位数字、一个破折号、3位数字、一个破折号和最后的4位数字。

var phone = "222-222-2222";
if (!/^'d{3}-'d{3}-'d{4}$/.test(phone)) {
  console.log("bad number");
} else {
  console.log("good number");
}

然后把你的代码改成:

if (!/^'d{3}-'d{3}-'d{4}$/.test(document.PizzaForm.phone.value)) {
    alert("Please provide a correct phone number.");
    document.PizzaForm.phone.focus();
}

如果您的电话号码格式更灵活,例如允许在区号周围加上括号,那么请参阅下面的更多解决方案:

  • http://www.regexplanet.com/advanced/javascript/index.html
  • https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html

在空白字段中设置提示"请输入电话号码"怎么样?

// This will treat empty strings, spaces and tabs as "empty"
function isEmpty(str){
    return !str.replace(/^'s+/g, '').length;
}
if (isEmpty(document.PizzaForm.phone.value)) {
    alert("Please enter a phone number.");
    document.PizzaForm.phone.focus();
} else if (!/^'d{3}-'d{3}-'d{4}$/.test(document.PizzaForm.phone.value)) {
    alert("Please provide a correct phone number.");
    document.PizzaForm.phone.focus();
}

假设这是您想要的模式(xxx-xxx-xxxx),包括破折号,这行得通:

function validatePhone(ipt){
  if(ipt.search('[0-9]{3}-[0-9]{3}-[0-9]{4}') === 0 && ipt.length === 12){
    return true;
  } else {
    return false;
  } 
}
console.log(validatePhone('123-456-7890'));
console.log(validatePhone('abc-def-ghij'));
console.log(validatePhone('123-456-789'));

当然,省略测试代码。

我实际上建议让他们使用破折号,斜杠或其他任何东西,然后将它们解析出来:

window.verify = function() {
  var phone = document.getElementById("phone").value.split("");
  var verified = "";
  for (var char in phone)
    {
       verified += parseInt(phone[char]) >= 0 ? phone[char] : "";
    }
  var len = verified.length;
  if (len != 7 && len != 10)
    {
      alert("Invalid number of digits!");
    }
  else
    {  // then format the resulting number as you see fit
      var finalNum = "";
      if (len == 10)
      {
         finalNum += verified.substring(0,3) + "-"  
         verified = verified.substring(3);
      }
      finalNum += verified.substring(0,3) + "-";
      verified = verified.substring(3);
      finalNum += verified;
      alert(""+finalNum);
    }
}
<input type="text" id="phone" />
<br>
<br>
<button type="button" onclick="verify()">Validate Phone</button>