sapan sapan - 6 months ago 25
Javascript Question

javascript cell number validation

I want to validate cell number using javascript.

Here is my code.

if(number.value == "") {
window.alert("Error: Cell number must not be null.");
number.focus();
return false;
}

if(number.length != 10) {
window.alert("Phone number must be 10 digits.");
number.focus();
return false;
}


Here is the issue, when i submit the form with out entering the phone number, it is showing the error cell number must not be null. it works fine.
when i submit the form with cell number less than 10 digits, it is showing phone number must be 10 digits. it is also fine.

The problem is when i submit the form with 10 digits, then also it is showing the error phone number must be 10 digits.

Please help me.
Thank You.

and also need the validation code for only digits for cell number.

Answer

If number is your form element, then its length will be undefined since elements don't have length. You want

if (number.value.length != 10) { ... }

An easier way to do all the validation at once, though, would be with a regex:

var val = number.value
if (/^\d{10}$/.test(val)) {
    // value is ok, use it
} else {
    alert("Invalid number; must be ten digits")
    number.focus()
    return false
}

\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.