Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript cell number validation

Tags:

javascript

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.

like image 633
sapan Avatar asked Sep 23 '13 01:09

sapan


1 Answers

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.

like image 110
tckmn Avatar answered Oct 13 '22 01:10

tckmn