In this article, I will show you how to validate 10 digit mobile number in javascript. input type="email" is enough to validate an email address. But to validate 10 degit mobile number, we have to add a condition in JavaScript using if statement.
We have a form and when the form is submitted, a JavaScript function is invoked.
Validation for 10 degit mobile number
<form class="event.preventDefault(); validate();">
<label>Mobile Number: </label><input type="number" id="my-input" placeholder="91#######" value="">
<input type="submit" value="submit">
</form>
<script>
function validate() {
const myInput = document.querySelector('#my-input');
if(myInput.value.length != 10) {
alert('10 digit mobile number is required');
}
}
</script>
Try it Yourself »
- event.preventDefault() is a JavaScript method that prevents the form from refreshing the current page. Read More
Comments (1)
10 digit mobile number validation in javascript
In this example, the pattern attribute is used to specify a regular expression pattern that ensures exactly 10 digits are entered. The [0-9] matches any digit, and {10} specifies that there should be exactly 10 occurrences of the preceding pattern. The required attribute makes sure the input field cannot be submitted empty. The small element provides a hint on the expected format.