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.