Home Courses Input Field Validation Message Using Blur Event

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:

  1. If the user enters less than 4 characters, a validation message will appear
  2. If the user enters more than 12 characters, another validation message will appear
  3. 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?

  1. It triggers when the user clicks outside the input field
  2. 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

  1. event.target.value gives the input field value
  2. onblur is better for validation compared to oninput (less annoying UX)
  3. textContent is used to update text inside elements
  4. style.display = "none" hides the message
  5. Always reset/hide validation messages when input becomes valid


Share this lesson: