Course contentsShow
← Web Development
Lesson 914 of 2,98216. Forms and ValidationFree lesson

Custom Validation on Input Events

Attach custom validation logic to input, change, and blur events for real-time feedback.

Custom Validation on Input Events

You'll learn how to attach custom validation logic to input, change, and blur events for instant, real-time user feedback.

The Core Idea

Instead of waiting until form submission to validate data, you can run your custom validation checks as the user types or interacts with form fields. By listening to input, change, and blur events, you create a responsive experience that guides users toward valid input immediately.

Think of it like a helpful coach standing beside you—correcting your form in real-time rather than waiting until after you've finished the entire workout.

Which Event to Choose?

  • input: Fires on every keystroke or value change. Best for immediate feedback (e.g., password strength).
  • change: Fires when the field loses focus and the value changed. Good for select boxes or final validation.
  • blur: Fires when the field loses focus, regardless of changes. Perfect for "validate when done typing" feedback.

Example Pattern

const emailField = document.getElementById('email');

emailField.addEventListener('input', (event) => {
  const value = event.target.value;
  
  if (!value.includes('@')) {
    emailField.setCustomValidity('Email must contain @');
  } else {
    emailField.setCustomValidity(''); // Clear error
  }
  
  emailField.reportValidity(); // Show validation message
});

Here, every keystroke triggers validation. The setCustomValidity() method you learned earlier applies the custom rule, and reportValidity() displays the feedback instantly.

Choosing the Right Moment

Use blur if you don't want to interrupt typing:

emailField.addEventListener('blur', () => {
  // Validate only after user leaves field
  if (emailField.value.length < 5) {
    emailField.setCustomValidity('Email too short');
    emailField.reportValidity();
  }
});

Key Takeaway: Attach custom validation to input, change, or blur events to provide real-time feedback, improving user experience by catching errors as they happen rather than at submission.