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
trueif the pressed key is a valid character andfalseotherwise.
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;
}

Join the conversation! Your thoughts help the community grow.