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

Combining Custom and Native Validation

Integrate custom validation logic with HTML5 constraints for a robust, layered validation approach.

Combining Custom and Native Validation

You'll learn how to layer custom validation logic on top of HTML5's built-in constraint validation to create a powerful, comprehensive validation system.

The Core Idea

Think of native validation as your first line of defense—it handles common cases like required fields, email formats, and number ranges automatically. Custom validation is your specialized backup that handles business rules and complex scenarios. When you combine them, native validation catches obvious problems instantly, while your custom logic adds the sophisticated checks that HTML5 can't handle alone.

The key is using setCustomValidity() alongside native constraints, not instead of them. Let native validation do the heavy lifting for basic checks, then add your custom rules on top.

How They Work Together

Start with native HTML attributes (required, type, pattern, etc.) to establish baseline validation. Then attach event listeners that run custom checks and call setCustomValidity() when your business rules fail. The browser merges both validation states—if either native or custom validation fails, the field is invalid.

const passwordField = document.getElementById('password');

// Native validation: required, minlength="8"
passwordField.addEventListener('input', () => {
  const value = passwordField.value;
  
  // Custom rule: must contain a number
  if (value && !/\d/.test(value)) {
    passwordField.setCustomValidity('Password must contain at least one number');
  } else {
    passwordField.setCustomValidity(''); // Clear custom error
  }
});

The native minlength still enforces minimum length, while your custom logic adds the number requirement. Both must pass for the field to be valid.

Why This Matters

This layered approach gives you robust validation with minimal code. Native validation handles standard cases efficiently, you only write custom logic for unique requirements, and users get consistent error reporting through the browser's validation UI.

Key Takeaway: Combine HTML5 constraint validation for standard checks with setCustomValidity() for custom rules—together they create a complete, maintainable validation system that leverages browser capabilities while meeting your specific business needs.