I need the code for 10-digit phone number validation in javascript. Is there any built-in function in Javascript to Validate the Phone number?
Mobile number validation is important to prevent fraud attacks. In this section, I will explain to you how to validate 10-digit phone number validation in Javascript. To check the mobile number validation, We have to use the if statement.
Try the following example:
<form> <input type="text" id="mobile_number" name="mobile_number"> <button type="submit" onclick="validateMobileNumber()">Submit</button> </form> <script type="text/javascript"> function validateMobileNumber(email) { var mobile_number = document.getElementById('mobile_number').value; if(mobile_number.length!=10){ alert('Mobile Number Digits should be 10'); } } </script>
This is another method to validate 10 digit phone number without using javascript
<form> <label for="phone">Enter a 10 digit phone number :</label><br> <input type="text" id="phone" name="phone" pattern="[0-9]{10}" required><br> <input type="submit" value="Submit"> </form>
Try this::
<script type="text/javascript"> var number = "0011223344"; var reg_pattern = new RegExp("^[0-9]{10}$"); var check = reg_pattern.test(number); console.log(check) </script>
The variable check returns either true or false. If the value is true, it means the pattern match is success the pattern is not correct
Here's the Javascript code to Validate the 10-digit phone number.
function validate10DigitPhoneNumber(phone_number) { if (typeof phone_number !== 'string') { // Check if the phone number is a string return false; } if (phone_number.length !== 10) { // Check if the phone number is exactly 10 digits long return false; } for (let i = 0; i < phone_number.length; i++) { // Check if all characters are digits if (!isNaN(phone_number[i])) { continue; } else { return false; } } // If all checks pass, the phone number is valid return true; }
Call like this:
let phone_number = '0123456789'; let is_valid = validate10DigitPhoneNumber(phone_number); console.log(is_valid); // Output: true