Phone number validation

Hi there, I need to validate three textboxes and it will validate for numbers. How should I change my code to validate three textboxes?

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <script type='text/javascript' language="javascript">

var validPhoneChar = "+";
// Minimum no of digits in an international phone no.
var minDigitsInPhoneNumber = 10;

function isInteger(s)
{   
    var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is a number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) 
            return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkRequirements(strPhone)
{
    if(strPhone.indexOf("+") > 1)
        return false;
    s = stripCharsInBag(strPhone,validPhoneChar);
    return (isInteger(s) && s.length >= minDigitsInPhoneNumber);
}

function ValidateForm()
{
    var Phone = document.getElementById("Text1");
    //var Phone1 = document.getElementById("Text23");
    if ((Phone.value == null)||(Phone.value == "")) //if match failed
    {
        alert("Please Enter your Phone Number.");
        Phone.focus();
            return false;
    }
    /*if ((Phone1.value == null)||(Phone1.value == "")) //if match failed
    {
        alert("Please Enter your Phone Number0.");
        Phone.focus();
            return false;
    }*/    
    if (checkRequirements(Phone.value) == false)
    {
        alert("Please Enter a Valid Phone Number.");
        Phone.value = "";
        Phone.focus();
            return false;
    }
    else    
        alert("YAY!");
    return true;
 }    
    
    
function NotAllowSpace()
{
    // Get the ASCII value of the key that the user entered
    var key = window.event.keyCode;

    // Verify if the key entered was a Space
    if ( key == 32 )
    {
        // If it was, then dispose the key and continue with entry
        window.event.returnValue = null; 
        alert("Invalid,Please check")
    }
    
    else
        // If it was not, then allow the entry to continue
        return;

}
    </script>
</head>
<body>
<label>Office Telephone:</label>
<input id="Text1" type="text" onkeydown = "return (event.keyCode != 32)"/><br />
<input id="Button1" type="button" value="button" onclick="return ValidateForm();" /><br />

</body>
</html>

I need to use Javascript to validate 3 textboxes, whereby the users can only key in numbers (because they are phone numbers related fields). If any of the textbox is empty, display an alert message to show which textbox is empty. I do not want to show many alert messages to show that, for example, text1 and text2 are empty, it will show two alert messages. I would need to show one “summarized” alert message instead.

Next, check if the textbox matches the pattern (which is to check if it has the skeleton of a phone number). If it is, show an alert message that it is alright. Else, show that it does not match.

Okay, so I’ve made the changes and the code is as below. But then, it has quite a lot of errors. Firstly, I would want it to show one alert message to show if all three textboxes are empty.

Also, it shows the alert message thrice when all three textboxes fulfil the requirements. (at least 8 digits, is an integer)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <script type='text/javascript' language="javascript">

var validPhoneChar = "+";
// Minimum no of digits in an international phone no.
var minDigitsInPhoneNumber = 8;

function isInteger(s)
{   
    var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is a number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) 
            return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkRequirements(strPhone)
{
    if(strPhone.indexOf("+") > 1)
        return false;
    s = stripCharsInBag(strPhone,validPhoneChar);
    return (isInteger(s) && s.length >= minDigitsInPhoneNumber);
}

function ValidatePhone(Phone)
{
    if ((Phone.value == null)||(Phone.value == "")) //if match failed
    {
        alert("Please Enter your Phone Number.");
        Phone.focus();
            return false;
    }

    if (checkRequirements(Phone.value) == false)
    {
        alert("Please Enter a Valid Phone Number.");
        Phone.value = "";
        Phone.focus();
            return false;
    }
    else    
        alert("YAY!");
    return true;
 }    

function ValidateForm()
{
    ValidatePhone(document.getElementById("Text1"));
    ValidatePhone(document.getElementById("Text2"));
    ValidatePhone(document.getElementById("Text3"));
}    
    
function NotAllowSpace()
{
    // Get the ASCII value of the key that the user entered
    var key = window.event.keyCode;

    // Verify if the key entered was a Space
    if ( key == 32 )
    {
        // If it was, then dispose the key and continue with entry
        window.event.returnValue = null; 
        alert("Invalid,Please check")
    }
    
    else
        // If it was not, then allow the entry to continue
        return;

}
    </script>
</head>
<body>

Office Telephone: <input id="Text1" type="text" onkeydown = "return (event.keyCode != 32)"/><br />
Mobile Telephone: <input id="Text2" type="text" onkeydown = "return (event.keyCode != 32)"/><br />
Home Telephone: <input id="Text3" type="text" onkeydown = "return (event.keyCode != 32)"/>
<input id="Button1" type="button" value="button" onclick="return ValidateForm();" /><br />

</body>
</html>

You should be aware that validation with javascript won’t stop bad values from going through. There are many people who don’t use scripting (a constant source or annoyance, and inspiration) as well as naughty people who will deliberately attempt to bypass security measures.

The only way that you can ensure that the validation is successful, is to perform it on the server side.

I suggest that you first get the validation working on the server, which on a bad validation will show the page again with suitable error messages, and only after that come back to javascript to perform the same validation so that the page reload doesn’t need to occur.

That way, you and your form will be safe.

Yes I know that javascript is not a good way. But I need it no matter what.

You could rename the validateform function to validatephone, which accepts each phone element from the form.

Then, a separate validateform function could pass each phone element to the validatephone function.

Huh? I don’t get what you mean. Could you explain? Thanks.

Here’s what I mean.

Take the existing ValidateForm function


function ValidateForm()
{
    var Phone = document.getElementById("Text1");
    //var Phone1 = document.getElementById("Text23");
    if ((Phone.value == null)||(Phone.value == "")) //if match failed
    ...
}

You’ll want to rename the ValidateForm function to ValidatePhone and remove the var Phone statements


function ValidatePhone(Phone)
{
    if ((Phone.value == null)||(Phone.value == "")) //if match failed
    ...
}

Then you can use a separate ValidateForm to pass the form elements to the ValidatePhone function.


function ValidateForm()
{
    ValidatePhone(document.getElementById("Text1"));
    ValidatePhone(document.getElementById("Text2"));
    ValidatePhone(document.getElementById("Text3"));
}

Then you’ll only want to use more proper coding techniques with the form itself, so that you can more easily interact with it instead of throwing up loads of alerts.

The ValidatePhone returns false on a failed validation, so from within the ValidateForm function you will want to check the value that the ValidatePhone function returns, and if it returns false, you know that you should return out of the ValidateForm function.

Could you explain more? I do not understand.

Right now the ValidateForm runs the ValidatePhone function three times in a row. This means that the ValidatePhone function is doing it’s thing three times over, and there is no way to stop it when something doesn’t validate.

You want to stop calling the ValidatePhone function when a previous call to it hasn’t validated. The ValidatePhone function returns true with a successful validation, and returns false with a failed validation.

You want the ValidateForm function to record the result from each call to the ValidatePhone function, and to check that result before the next call is made to ValidatePhone.

If the recorded result from ValidatePhone is true then it is okay to carry on and call ValidatePhone for the next field. If it’s false though, you know that the most recent call to ValidatePhone found something wrong, so you won’t want to carry on with the other ones. When the returned valud is false you will want to return out of the ValidateForm instead of carrying on.

Okay, can you guide me on how to change my code? I am seriously stuck for I have just started Javascript.

Just providing the code on a platter will not allow any learning to occur. So instead, I invite you to make the changes yourself, and we will help you with any coding issues that you have.

Currently, you want to assign the returned result from ValidatePhone to a variable, and then to check if that variable is false. If it is false then you need to return out out the ValidateForm instead of allowing execution to continue on to the next ValidatePhone call.

Uh, can you explain everything in simpler terms? I am bewildered. Do you mean it this way (by assigning the result to a variable?)

function ValidatePhone(Phone)
{
    var result = Phone.Value;
    if ((Phone.value == null)||(Phone.value == "")) //if match failed
    {
        alert("Please Enter your Phone Number." + result);
        Phone.focus();
            return false;
    }

    if (checkRequirements(Phone.value) == false)
    {
        alert("Please Enter a Valid Phone Number." + result);
        Phone.value = "";
        Phone.focus();
            return false;
    }
    else    
        alert("YAY!");
    return true;
 }    

No, leave the ValidatePhone function alone. That does its job well. It’s the ValidateForm function that your attention need to be directed to.

Okay, can you please explain what I need to modify in the ValidateFunction? I seriously do not know what I should modify.

You know how the ValidateForm function contains three calls to ValidatePhone ?
You need to check if the returned result from calling ValidatePhone is equal to false. If it is false, you know that you need to return out of the ValidateForm function, which will prevent the other unwanted calls to ValidatePhone from occurring.

sigh. I am totally clueless about how to start editing. I have actually put if(document.getElementById(“Text1”).value == “”) after

ValidatePhone(document.getElementById(“Text1”));

but then, it is not working. I wanted to check if Text1 is empty, but then wouldn’t it be doing the same as ValidatePhone?

It’s the ValidatePhone function that you’ll want to check.

You can do it in one of two ways.

You can assign the result of ValidatePhone to a variable, perhaps called isValid, and then check if that variable called isValid is false, or you can avoid the double-duty and just place the call to ValidatePhone in the condition itself.

Here are some examples using a function called someFunc as an example.


var isValid = someFunc();
if (isValid === false) {
    return;
}

or


var isValid = someFunc();
if (!isValid) {
    return;
}

or


if (!(someFunc())) {
    return;
}

or


if (someFunc() === false) {
    return;
}

or even


if (!someFunc()) {
    return;
}

Seriously, I am very confused about what I need to do. I don’t know where to modify: do I modify in ValidateForm or ValidatePhone(Phone)?

I cannot grasp what you are trying to explain.

The ValidateForm function is the one that you modify. If the ValidatePhone function returns false to the ValidateForm, you want to return out of the ValidateForm so that the other calls to ValidatePhone don’t occur.

As I’m having a difficult time getting this information across to you, if you’re taking a course on this the tutor will have more information for you regarding this. Otherwise, there are many good books in learning JavaScript that we can point you to.

There has also recently been a good thread about choosing which books to read, at http://www.sitepoint.com/forums/showthread.php?t=660198