简体   繁体   中英

Javascript Phone number Format

It seems that my original question was closed out. I was able to complete most of the form validation requirement for my Pizza form. However now I'm just stuck at the phone number validation and format.

I need assistants for form validation for my phone number.

The phone number must be Numbers only with Dash for example 222-222-2222 and anything else besides that format or an empty field should cause an alert when I hit my submit button and doe snot allow the form to be submitted unless it is correct

Please review my code for document.PizzaForm.phone.value code for my pizza form I'm not sure how to edit the code to achieve my requirement.

<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>

Assuming that's the pattern you want (xxx-xxx-xxxx), including the dashes, this works:

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'));

Of course, leave out the testing code.

The phone number must be Numbers only with Dash for example 222-222-2222

You can use a regex to check your phone number. This will match exactly 3 digits, a dash, 3 digits, a dash, and a final 4 digits.

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

Then change your code to this:

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

If you are more flexible on your phone number format, for example allowing brackets around the area code, then please see below for more solutions:


What about an alert for a blank field that says please enter phone number?

// 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();
}

I actually recommend letting them use dashes, slashes, or whatever, then just parsing them out:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM