views:

344

answers:

4

I need to validate a phone number in javascript. The requirements are:

they should be 10 digits, no comma, no dashes, just the numbers, and not the 1+ in front

this is what I wrote so far

function validatePhone(field,alerttxt) {
    with (field) {
        if(value.length > 10) {
            alert(alerttext);
            return false;
        }
        for(i = 0; i < value.length; i++) {
            if(parseInt(value[i]) == NaN) {
                alert(alerttxt);
                return false;
            }
        }
        return true;
    }
}
function validateForm(thisform) {
        if (validatePhone(phone,"Invalid phone number")==false) {
            phone.focus();
            return false;
        }

    }
}
  <form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
    <ol>
        <label for="phone">Your phone <span class="red"></span></label>
        <input id="phone" name="phone" class="text" />
      </li>
    </ol>
  </form>

but, obviously it doesn't work. How can I write the validatePhone() function so that it works?

A: 

Fixed function:

function validateForm(thisform) {
        if (validatePhone(thisform.phone,"Invalid phone number")==false) {
            thisform.phone.focus();
            return false;
        }
        return true;
}
antyrat
I forgot to include with(thisform) at the beginning of the function, but actually I wrote it)
klez
But you also have extra "}" symbol
antyrat
+3  A: 
phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) { 
   alert("not 10 digits");
} else {
  alert("yep, its 10 digits");
} 

This will validate and/or correct based on your requirements, removing all non-digits.

Erik
Why not just use match?
Marius
as I said "validate and/or correct" is why not just match. Its pretty poor user experience to force someone to enter a phone number sans spaces or dashes when they are so easy to remove.
Erik
thanks, I really like the 'corrective' regex :-)
klez
A: 

use IS_NUMERIC to check the number it return true or false...

Is_Numeric

Marcx
This function is pretty horrible. It will call -6 non-numeric (any negative number, actually), it also fails on 1e4 which should return numeric, and it says 5.5.52 is numeric.
Erik
+4  A: 

You could use Regular Expressions:

function validatePhone(field,alerttxt) {
    if (field.match(/^\d{10}/)) {
         return true;
    } 
    alert(alerttext);
    return false;
}
arnep