JQuery  

Implementing Robust Email and Mobile Number Validation with jQuery

When it comes to web form validation, especially for sensitive information like email addresses and mobile numbers, ensuring that the data entered by users is valid and properly formatted is essential. Client-side validation helps reduce errors and enhances the user experience by providing immediate feedback.

In this article, we’ll break down how to implement comprehensive email and mobile number validation using jQuery. The provided solution validates both email formats and mobile number formats, with added checks for things like sequential digits, keyboard patterns, and repeated characters. Let’s walk through the code and its functionality.

Key Features of the Solution

  1. Mobile Number Validation

    • The number must be exactly 10 digits.

    • The number must start with a digit between 7 and 9.

    • Disallows numbers with identical digits (e.g., 1111111111).

    • Disallows ascending or descending sequences (e.g., 1234567890, 0987654321).

  2. Email Validation

  3. Dynamic Form Validation

    • The form is validated when the user interacts with the form fields (via change events).

    • Provides immediate feedback during user input (via onblur, onchange, and onkeypress events).

    • The form only submits if both the email and mobile number fields are valid.

Understanding the Code

Here is the full JavaScript solution that performs the validation logic on both email and mobile number fields.

Step 1: jQuery Document Ready

$(document).ready(function () {
    // Use 'change' event for validation
    $("#<%= txtemail1.ClientID %>").change(function () {
        validateEmail(this);
    });

    $("#<%= txtcontactno1.ClientID %>").change(function () {
        validateMobile(this);
    });

    // Handle form submission validation
    $("#<%= btnsignup1.ClientID %>").click(function () {
        return validateForm();
    });
    $("#<%= EMaildId.ClientID %>").change(function () {
        validateEmail(this);
    });

    $("#<%= MobileID.ClientID %>").change(function () {
        validateMobile(this);
    });

    // Handle form submission validation for feedback form
    $("#<%= SubmitFeeId.ClientID %>").click(function () {
        return validateFeedbackForm();
    });
});
  • What’s happening here?

    • $(document).ready(function()) ensures that the validation runs when the DOM is fully loaded.

    • The change event is used to trigger the validation functions (validateEmail and validateMobile) whenever the user changes the content of the email or mobile input fields.

    • The click event is used to handle form submission validation before actually submitting the form.

Step 2: Mobile Number Validation

function validateMobile(input) {
    var value = input.value.trim();
    $(input).removeClass("abc1");

    // Skip validation if field is empty
    if (value === "") return true;

    // Must be exactly 10 digits
    if (!/^\d{10}$/.test(value)) {
        alert("Mobile number must be exactly 10 digits.");
        $(input).addClass("abc1");
        return false;
    }

    // Must start with 7, 8, or 9
    if (!/^[7-9]/.test(value)) {
        alert("Invalid mobile number. It should start with a digit from 7 to 9.");
        $(input).addClass("abc1");
        return false;
    }

    // All digits the same are not allowed
    if (/^(\d)\1{9}$/.test(value)) {
        alert("Invalid mobile number. All digits cannot be the same.");
        $(input).addClass("abc1");
        return false;
    }

    // Block full ascending or descending sequence
    if (value === "1234567890" || value === "0987654321") {
        alert("Invalid mobile number. Sequential digits not allowed.");
        $(input).addClass("abc1");
        return false;
    }

    return true;
}
  • Mobile Validation Breakdown:

    • Length Check: It ensures that the mobile number is exactly 10 digits.

    • Starting Digit Check: It verifies that the number starts with a digit between 7 and 9 (e.g., 7012345678 is valid, but 6012345678 is not).

    • Identical Digits Check: Prevents numbers like 1111111111.

    • Sequential Digits Check: Blocks numbers like 1234567890 or 0987654321.

Step 3: Email Validation

function validateEmail(input) {
    var value = input.value.trim().toLowerCase();
    $(input).removeClass("abc1");

    // Skip validation if the field is empty
    if (value === "") return true;

    var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(value)) {
        alert("Please enter a valid email address.");
        $(input).addClass("abc1");
        return false;
    }

    var localPart = value.split('@')[0];

    // Check for repeated characters
    if (/^(.)\1+$/.test(localPart)) {
        alert("Invalid email. Repeated characters not allowed.");
        $(input).addClass("abc1");
        return false;
    }

    // Check for sequential letters
    for (var i = 0; i <= localPart.length - 3; i++) {
        var c1 = localPart.charCodeAt(i);
        var c2 = localPart.charCodeAt(i + 1);
        var c3 = localPart.charCodeAt(i + 2);

        if ((c2 === c1 + 1 && c3 === c2 + 1) ||  // ascending
            (c2 === c1 - 1 && c3 === c2 - 1)) {  // descending
            alert("Invalid email. Sequential letters not allowed.");
            $(input).addClass("abc1");
            return false;
        }
    }

    // Additional checks for repeated patterns and keyboard patterns
    for (var subLen = 2; subLen <= 4; subLen++) {
        for (var i = 0; i <= localPart.length - subLen * 2; i++) {
            var pattern = localPart.substr(i, subLen);
            var nextPattern = localPart.substr(i + subLen, subLen);
            if (pattern === nextPattern) {
                alert("Invalid email. Repeating patterns not allowed.");
                $(input).addClass("abc1");
                return false;
            }
        }
    }

    var repeatCount = 1;
    for (var i = 1; i < localPart.length; i++) {
        if (localPart[i] === localPart[i - 1]) repeatCount++;
        else repeatCount = 1;

        if (repeatCount >= 4) {
            alert("Invalid email. Too many repeated characters.");
            $(input).addClass("abc1");
            return false;
        }
    }

    var keyboards = ["qwertyuiop", "asdfghjkl", "zxcvbnm", "poiuytrewq", "mnbvcxz", "lkjhgfds"];
    for (var k = 0; k < keyboards.length; k++) {
        var seq = keyboards[k];
        if (localPart.includes(seq) || localPart.includes(seq.split("").reverse().join(""))) {
            alert("Invalid email. Keyboard pattern detected.");
            $(input).addClass("abc1");
            return false;
        }
    }

    $(input).removeClass("abc1");
    return true;
}
  • Email Validation Breakdown:

    • General Email Format Check: It verifies if the email follows the correct structure using a regular expression.

    • Repeated Characters Check: Disallows emails like [email protected].

    • Sequential Characters Check: Prevents emails like [email protected].

    • Repeated Patterns Check: Detects emails with repeated patterns (e.g., [email protected]).

    • Keyboard Pattern Check: Detects email addresses that are based on keyboard patterns (e.g., [email protected]).

Step 4: Form Validation Before Submission

function validateForm() {
    var isValid = validateEmail($("#<%= txtemail1.ClientID %>")[0]) &&
        validateMobile($("#<%= txtcontactno1.ClientID %>")[0]);
    return isValid;
}

function validateFeedbackForm() {
    var isValid = validateEmail($("#<%= EMaildId.ClientID %>")[0]) &&
validateMobile($("#<%= MobileID.ClientID %>")[0]);
return isValid;
}
       

Form Submission Validation:

The form will only be submitted if both the email and mobile number are valid. This is achieved by checking both fields and ensuring each returns true for validation.

Conclusion

By using this solution, you ensure that your forms are protected against invalid email addresses and mobile numbers, improving both data quality and user experience. The validation checks are thorough, preventing common pitfalls such as repeated characters, sequential digits, and keyboard patterns. This approach provides immediate feedback to users as they fill out the form, allowing them to correct mistakes before submitting the data.