ASP.NET  

Validating User Input in Forms with JavaScript and ASP.NET

When designing web applications, ensuring that user inputs are properly validated is crucial to prevent erroneous data submissions. A typical example is a Contact Us form where users provide sensitive information like their email address and phone number. To ensure data accuracy, we can employ client-side validation techniques. Below is an article that explains how to create a contact form with robust validation for both email and mobile number fields using JavaScript and ASP.NET controls.

Introduction

In this article, we'll walk through the process of validating email and phone number inputs in a Contact Us form. We'll use JavaScript for validation and ASP.NET controls for the form structure. This will ensure that users input valid email addresses and phone numbers before submitting the form.

The form will include two primary input fields:

  • Email Address

  • Mobile Number

Both fields will have specific validation rules, such as checking for correct formats, rejecting sequential numbers or letters, and disallowing repeated characters.

HTML Structure: Contact Us Form

Here's the basic structure of the contact form built using ASP.NET controls:

<!-- Contact Us Form -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 showblock nopad" runat="server" id="contactus_dis" style="font-size: 21px;">
    <asp:Panel ID="panelsigup" runat="server" DefaultButton="btnsignup1">
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopad">
            <div class="footer_title col-xs-12 col-sm-12 col-md-12 col-lg-12 nopad" id="addclass2">
                We will share you more information 
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 nopad" id="addclass">
            <div class="col-md-3 col-sm-3 col-xs-12 nopad">
                <asp:TextBox ID="txtemail1" runat="server" placeholder=" My email-id" CssClass="txt_bx tstcc foot_text textmail"
                    onblur="data_function(this)" MaxLength="60"></asp:TextBox>
            </div>
            <div class="col-md-2 col-sm-3 col-xs-12 nopad">
                <asp:TextBox ID="txtcontactno1" runat="server" placeholder=" My contact no" CssClass="txt_bx tstcc foot_text textno"
                    onblur="data_function(this)" MaxLength="15" onkeypress="return isNumberKey(event);"></asp:TextBox>
            </div>
            <div class="col-md-2 col-sm-2 col-xs-12 nopad">
                <asp:Button ID="btnsignup1" runat="server" Text="Get Details" CssClass="btn" OnClientClick="return validateForm();"
                    OnClick="btn1_signup" />
            </div>
        </div>
    </asp:Panel>
</div>
  • txtemail1 – Email input field.

  • txtcontactno1 – Mobile number input field.

  • btnsignup1 – Submit button with validation.

JavaScript Validation Logic

We'll now explain the JavaScript code that ensures the email and mobile number are entered correctly.

Mobile Number Validation

The validateMobile() function checks the following:

  • The number must be exactly 10 digits.

  • It cannot consist of identical digits (like 1111111111).

  • It cannot contain sequential digits (like 1234567890 or 9876543210).

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

    // Skip validation if the field is empty (user hasn't entered anything yet)
    if (value === "") return true;

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

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

    // Check for sequential digits
    for (var i = 0; i <= value.length - 3; i++) {
        var d1 = parseInt(value[i]);
        var d2 = parseInt(value[i + 1]);
        var d3 = parseInt(value[i + 2]);

        if ((d1 + 1 === d2 && d2 + 1 === d3) || // ascending
            (d1 - 1 === d2 && d2 - 1 === d3)) { // descending
            alert("Invalid mobile number. Sequential digits not allowed.");
            $(input).addClass("abc1");
            return false;
        }
    }

    return true;
}

Email Validation

The validateEmail() function ensures:

  • The email must follow the standard format (e.g., [email protected]).

  • The local part of the email (before the @) cannot have repeated characters (like aaaaaaa).

  • It cannot contain sequential characters (like abc or xyz).

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

    // Skip validation if the field is empty (user hasn't entered anything yet)
    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];

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

    // Check for sequential letters in email's local part
    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;
        }
    }

    return true;
}

Form Submission Validation

The validateForm() function ensures that both email and mobile number validations pass before form submission. It checks both fields and prevents submission if either is invalid.

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

Conclusion

With the above setup, users are presented with a contact form that validates both the email address and mobile number fields to ensure that they meet certain criteria. This improves the quality of the data being submitted and helps avoid issues related to invalid or poorly formatted information.

Advantages of Client-Side Validation:

  • Immediate feedback: Users are informed of errors immediately without needing to submit the form.

  • Enhanced user experience: Provides a smoother experience by preventing the need for reloading the page to fix errors.

  • Prevents basic errors: It filters out common mistakes like invalid email formats, mobile number sequences, or repeated characters before the form is submitted.

By implementing JavaScript validation alongside ASP.NET controls, you can ensure that only valid data is sent to your server, which reduces errors and improves the security of your application.