×

Please Login or Register to continue.

1
(124 Views)

I am creating an HTML form and want to validate the mobile number using the JS jQuery library. The mobile number should be 10 digits only. Mobile numbers should not start with zero 0 or any space. If someone enters zero at the starting of the number it should give a message to the user that entered the correct mobile number. This message can be shown below the mobile text box or alert message using the JS alert function.   The mobile number is at least 10 digits without special characters and country code. 

 

 

(7.4K Points)
in jquery

Share

1 Answer
(9.4K Points)
(edited)
0

Validation plays an important role in dynamic website creation. If you need mobile validation then you should consider points below. 

1. The mobile number should be 10 digit number. 

2. Mobile numbers shouldn't start with zero 0 or if you need to start with 0. 

3. No whitespace in mobile numbers. 

4. No special characters in mobile numbers. 

5. No country code at the beginning of the mobile number. 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mobile Number Validation</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .error {
            color: red;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <label for="mobile">Enter Mobile Number:</label>
    <input type="text" id="mobile" maxlength="10">
    <p id="message" class="error"></p>
    
    <script>
        $(document).ready(function(){
            $("#mobile").on("input", function(){
                let mobile = $(this).val();
                let regex = /^[1-9][0-9]{9}$/; // 10 digits, no leading 0, no spaces, no special chars, no country code
                
                if (!regex.test(mobile)) {
                    $("#message").text("Invalid mobile number. It must be 10 digits, cannot start with 0, and have no spaces or special characters.");
                } else {
                    $("#message").text("");
                }
            });
        });
    </script>
</body>
</html>

 

The main code line is 

regex = /^[1-9][0-9]{9}$/; // 10 digits, no leading 0, no spaces, no special chars, no country code 

This is a regular expression to validate mobile numbers. 

If you need to consider 0 zero at the beginning  

 

/^(0?[1-9][0-9]{9})$/   10 digits,  leading 0, no spaces, no special chars, no country code 

Make sure to increase the input number

<input type="text" id="mobile" maxlength="11">

 In this way, you can validate mobile numbers in jQuery. 

 


Comment


Related Questions :-

Your Answer

You can post your answer after login..

Live Chat

Hello! How can we assist you today?