Javascript - Form Validation

Soldato
Joined
27 Jun 2006
Posts
6,333
Hello folks,

Trying to put together a form here but having a bit of trouble with the phone number element. I have taken a code relative to US numbers and turned it UK friendly. Or tried to.

This is the code I have now:

Code:
function formatNumber(){
    var theNumbersOnly = "";
    var theChar = "";
    var theInput = document.phoneform.phone.value;
    
    for (i = 0; i < theInput.length; i++){
        theChar = theInput.substring(i,i+1);
        if (theChar >= "0" && theChar <= "12"){
            theNumbersOnly = "" + theNumbersOnly + theChar;
        }
    }
    
    if (theNumbersOnly.length < 13){
        alert("You must enter 13 numbers.");
        document.phoneform.phone.focus();
    }else{
        var areacode = theNumbersOnly.substring(0,2);
        var exchange = theNumbersOnly.substring(2,5);
        var extension = theNumbersOnly.substring(5,13);
        var newNumber = "(" + areacode + ") ";
        newNumber += exchange + "-" + extension;

        document.phoneform.phone.value = newNumber;
    }
}

Code:
Phone Number*: <input type = "text" name = "phoneform" value="(44) 028 38333333" size = 30 onchange="formatNumber();">

I have only changed numbers but the code now happily (and wrongly) accepts letters on submit, when I would obviously want to it to proudly display the error message: You must enter 13 numbers.

Any idea what might be wrong? I'm very new to Javascript so this is no doubt an easy question.

I removed the <form name="phoneform"> </form from the original code, this may have affected it?

I've also changed the name = "phoneform" to name = "phone" but still the same story.

Thanks for any help.
 
Stick
alert(theInput);

just below the
var theInput = document.phoneform.phone.value;
line.

I guess it will say [nothing]

you removed the phoneform Form so it can't find the text box.
Anyway, try using
document.getElementById('phone');
instead.

also theChar only contains 1 character so theChar <= "12" will pretty much always succeed.

oh and my home phone number is <13 numbers as is my work number and pretty much any number in London.

find a UK valudating script online and use that instead. Or use regex (http://regexlib.com/):

^0\d{2,4}[ -]{1}[\d]{3}[\d -]{1}[\d -]{1}[\d]{1,4}$

Simon
 
Last edited:
Back
Top Bottom