Validation for 10 digit mobile number and focus input field on invalid

Validation for 10 digit mobile number and focus input field on invalid

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Enforcing Mobile Number Constraints and Handling Invalid Input

When building a contact form, simply marking a field as required is rarely enough to ensure data quality. A user might enter "1234567890" into a mobile number field, which passes HTML5 validation if the format isn't explicitly checked, or they might paste an email address by mistake. To catch these errors before the request hits your server, you need client-side logic that validates specific constraints and provides immediate visual feedback.

The core requirement here is twofold: validate that the mobile number contains exactly ten digits, and programmatically shift focus back to that field if the validation fails. This approach improves the user experience by preventing form submission with bad data and guiding the user immediately to where they made a mistake.

Defining the Validation Logic

Before writing any JavaScript, we must define what constitutes a valid 10-digit mobile number in this context. We are looking for a string that contains only numeric characters and has a length of exactly 10. Leading or trailing spaces often break simple regex patterns, so trimming the input is a necessary first step.

Using jQuery, we can attach an event listener to the form's submit action. At this point, the browser has already performed its initial HTML5 checks (like ensuring the field isn't empty), but our custom logic runs on top of that. We extract the value from the #mobile input, trim whitespace, and test it against a regular expression.

$('#enquiry_form').on('submit', function(e) {
    var mobileNumber = $('#mobile').val().trim();
    
    // Regex explanation: ^ ensures start of string, \d matches any digit 0-9, 
    // {10} enforces exactly 10 repetitions, $ ensures end of string.
    var isValid = /^\d{10}$/.test(mobileNumber);

    if (!isValid) {
        e.preventDefault(); // Stop the form from submitting
        
        // Visual feedback: Highlight the error
        $('#mobile').css('border-color', 'red');
        
        // Focus on the invalid field immediately
        $('#mobile').focus();
        
        // Optional: Show a tooltip or message explaining the error
        var message = "Please enter a valid 10-digit mobile number.";
        $('#mobile').after('<div class="error-message">' + message + '</div>');
    } else {
        // Clean up styling if validation passes (optional but recommended)
        $('#mobile').css('border-color', ''); 
        $('.error-message').remove();
    }
});

The regular expression /^\d{10}$/ is the linchpin here. The ^ and $ anchors ensure that we are matching the entire string, not just a substring within it. Without these, an input like "555-1234" or "1234567890 extra text" might partially match depending on how the test is written. The {10} quantifier is strict; it rejects 9-digit numbers and 11-digit numbers, which is crucial for many international formatting standards where country codes are excluded from the mobile number itself.

Handling Edge Cases and User Experience

A common pitfall in this scenario is how the user interacts with the input field after an error. When you call .focus(), the browser moves the cursor to the beginning of the input box. If the user was in the middle of typing, they lose their place. However, since we are preventing the form submission due to invalid data, the user likely hasn't finished entering their number yet, or they have entered garbage text.

In this specific case, focusing on the field is the correct behavior because it signals, "Fix this before you proceed." The red border provides a strong visual cue, and the focus ensures the keyboard (on mobile devices) opens immediately to the correct state.

There is also the matter of input type. The source HTML uses type="number" for the mobile field. While this restricts the keyboard to digits on mobile devices, it can sometimes trigger the native number spinner UI in desktop browsers. For a strict 10-digit requirement without country codes, type="text" combined with the regex validation is often safer. The type="number" input can sometimes coerce values (e.g., converting "0123" to ".123" or stripping leading zeros) depending on browser implementation, which would cause your regex check to fail unexpectedly.

If you decide to stick with type="number", be aware that the HTML5 validation API has its own built-in pattern checking. You can pair the custom jQuery logic with the native oninvalid event to handle cases where the user clicks away from the field but hasn't yet submitted the form. This layered approach ensures that invalid data is caught both on blur (when leaving the field) and on submit.

For developers looking for more robust validation strategies or ready-made components that handle these edge cases gracefully, resources like https://laravelcompany.com often provide insights into integrating backend rules with frontend validation, ensuring that what the client accepts aligns with what the server processes.

Our network