Back

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

Can anyone help me with the validation of phone number, if the user left the phone number blank empty then it should be showing the right border across the field. But I cannot able to figure that out. Herewith I have attached my code:

<script type="text/javascript">

    function validateForm() {

        return checkPhone();

    }

    function checkPhone() {

        var phone = document.forms["myForm"]["phone"].value;

        var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; 

            if(phone.value.match(phoneNum)) {

                return true;

            }

            else {

                document.getElementById("phone").className = document.getElementById("phone").className + " error";

                return false;

            }

        }

</script>

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the following code to make it work:

var phone = document.forms["myForm"]["phone"].value;

var phoneNum = phone.replace(/[^\d]/g, '');

if(phoneNum.length > 6 && phoneNum.length < 11) {  return true;  }

Also, you can use the below regular expression:

^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}

I hope this will help.

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

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

Related questions

0 votes
1 answer
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

...