ASP.NET  

Form Validation with onchange, blur, alpha, and numeric Validation

In modern web development, form validation plays a crucial role in ensuring that the data entered by users is correct and consistent. Validating user input on form fields such as text boxes, phone numbers, or names improves both user experience and data integrity.

In this article, we'll walk through a piece of JavaScript code that handles various form validation tasks, including length checks, alpha (letters only) and numeric (numbers only) validation, as well as ensuring that no unwanted spaces are entered. We will also cover how onchange, blur, and other event listeners are used to trigger these validations.

Code Breakdown: Event Handlers and Validation Functions

1. checklength() Function:

This function validates that the length of the text entered into a particular text box (presumably for a comment or message) does not exceed a set character limit of 500 characters.

function checklenght() {
    var textbox = document.getElementById("<%=txtcomment.ClientID%>").value;
    if (textbox.trim().length >= 500) {
        return false;
    } else {
        return true;
    }
}
  • Purpose: It ensures that the user cannot enter more than 500 characters.

  • How it works:

    • The function fetches the value of the input field using document.getElementById("<%=txtcomment.ClientID%>").value.

    • It checks if the length of the string (after trimming any leading or trailing whitespace) exceeds 500.

    • If the length is greater than or equal to 500, it returns false, preventing the form submission or input field updates.

2. isAlphaCheck1() Function:

This function validates that the user can only enter alphabetical characters (letters) in a given input field, such as a name or company name.

function isAlphaCheck1(ctrlid, evt) {
    var k = (evt.which) ? evt.which : evt.keyCode;
    var len = document.getElementById(ctrlid.id).value.length;
    if (len <= 0)
        return ((k >= 65 && k <= 90) || (k >= 97 && k <= 122) || k == 8 || k == 9) ? true : false;
    else
        return ((k >= 65 && k <= 90) || (k >= 97 && k <= 122) || (k >= 32 && k < 33) || k == 8 || k == 9) ? true : false;
}
  • Purpose: This function restricts the input to alphabetical characters only.

  • How it works:

    • The event listener checks the key code (pressed key) when the user types into the input field.

    • If the input field is empty, the function allows only letters (A-Z, a-z) or backspace/Tab key (for editing).

    • If the field already has some content, it also allows spaces, letters, or the backspace/Tab key.

    • The function returns true if the pressed key is a valid character and false otherwise.

3. isNumberKey() Function:

This function ensures that only numeric input is allowed in a field, such as a phone number or age field.

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
  • Purpose: It restricts the input to numeric characters only (0-9).

  • How it works:

    • The event listener checks the key code of the pressed key.

    • It allows numeric values (0-9), backspace, and Tab.

    • Any other keys (letters or special characters) will be ignored by returning false.

4. no_space() Function:

This function removes any special characters or spaces from the input text.

function no_space(txt) {
    if (txt.value.match(/\s/g) !== null) {
        txt.value = txt.value.replace(/[\W]/g, '');
    }
}
  • Purpose: It removes any non-alphanumeric characters (special characters) and spaces from the input field.

  • How it works:

    • The match(/\s/g) checks if the value contains any spaces (\s).

    • If spaces are found, the function replaces them with an empty string (''), effectively removing them.

5. data_function() Function:

This function adds or removes a specific CSS class to an input element based on certain conditions, like validation or styling changes.

function data_function(value) {
    var value1 = document.getElementById(value.id);
    $(value1).removeClass("abc1");
    $(value1).addClass("");
}
  • Purpose: This function is used to apply/remove CSS classes based on user interactions.

  • How it works:

    • The data_function() function is called on events like blur, removing any existing error class (abc1) from the field and applying a blank class (or new class).

HTML Structure for Form Fields

The form contains several input fields where the validation functions are applied:

<div class="form_div_box1 clear">
    <div class="process_div">
        <div class="col-sm-6 col-xs-12 col_input_name node_rgt">
            <asp:TextBox ID="Fname" runat="server" CssClass="fname" MaxLength="80" placeholder="Company Name" onblur="data_function(this)" onkeypress="return isAlphaCheck1(this, event)"></asp:TextBox>
        </div>
        <div class="col-sm-6 col-xs-12 col_input_name">
            <asp:TextBox ID="Lname" runat="server" CssClass="lname" MaxLength="40" placeholder="Company Contact Person Name" onblur="data_function(this)" onkeypress="return isAlphaCheck1(this, event)"></asp:TextBox>
        </div>
    </div>

    <div class="process_div">
        <div class="col-sm-4 col-xs-12 col_input_name info node_rgt">
            <asp:TextBox ID="infocompany" runat="server" CssClass="infoN" MaxLength="80" placeholder="Company Name" onblur="data_function(this)" onkeypress="return isAlphaCheck1(this, event)"></asp:TextBox>
        </div>
        <div class="col-sm-6 col-xs-12 col_input_name cmp node_rgt">
            <asp:TextBox ID="Contact1" runat="server" CssClass="contact1" MaxLength="15" placeholder="Mobile No." onblur="data_function(this)" onkeypress="return isNumberKey(event)"></asp:TextBox>
        </div>
    </div>
</div>
  • Fname and Lname: These fields use isAlphaCheck1 for restricting input to alphabetic characters (company name, contact person).

  • infocompany: Similar to Fname and Lname, it accepts only letters.

  • Contact1: This field accepts numeric input only, and it uses isNumberKey to ensure that only numbers are entered.

Summary

In this article, we’ve covered the implementation of a variety of input validation techniques using JavaScript and jQuery to enhance form fields. Here's a recap of the key elements:

  1. checklength() ensures that the entered comment does not exceed 500 characters.

  2. isAlphaCheck1() limits input to alphabetical characters for names and company fields.

  3. isNumberKey() restricts input to numbers only, ideal for mobile numbers or other numeric fields.

  4. no_space() removes spaces and special characters from the text input.

  5. data_function() is used to handle styling changes after validation.