Input Field Validation Message Using Blur Event
Create validation messages for an input field using JavaScript.
What are we building?
We will create an input field where:
- If the user enters less than 4 characters, a validation message will appear
- If the user enters more than 12 characters, another validation message will appear
- If the input is valid, the message will disappear
You can adjust the minimum and maximum length as per your requirement.
Key Concepts Covered
Input Field Setup
We create an input field and attach a validation function using the onblur event.
<input type="text" onblur="validateInputField(event)" id="user" placeholder="Enter User Name">
Why onblur?
- It triggers when the user clicks outside the input field
- It provides a better user experience compared to validating on every keystroke
Validation Message Element
We use a <span> to display validation messages.
<span style="color: red;" id="user-message"></span>
Validation Logic
We check the length of the input value and display messages accordingly.
function validateInputField(event) {
let val = event.target.value;
let validateEl = document.getElementById('user-message');
// Make sure message is visible
validateEl.style.display = "block";
if (val.length < 4) {
validateEl.textContent = "min valid length is 4";
}
else if (val.length > 12) {
validateEl.textContent = "max valid length is 12";
}
else {
validateEl.textContent = "";
validateEl.style.display = "none";
}
}
Important Points
event.target.valuegives the input field valueonbluris better for validation compared tooninput(less annoying UX)textContentis used to update text inside elementsstyle.display = "none"hides the message- Always reset/hide validation messages when input becomes valid