Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me how I can able to validate the cell number using JavaScript? Herewith I have attached my code which is given an error even after I was entering 10 digits for phone number:

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;

}

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use regex for validation which help me a very easy way to do that:

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

}

I hope this will help.

Want to know more about Java? Prefer this tutorial on Java Tutorial.

Want to become a Java Expert? Join Java Training now!!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 4, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...