DEV Community

Cover image for Day 15/180 of Frontend Dev: Mastering HTML5 Input Types & Validation
CodeWithDhanian
CodeWithDhanian

Posted on

Day 15/180 of Frontend Dev: Mastering HTML5 Input Types & Validation

Welcome to Day 15 of the 180 Days of Frontend Development Challenge. Today we'll explore modern HTML5 input types and professional validation techniques that create seamless user experiences. For comprehensive form strategies, see the Learn Frontend Development in 180 Days ebook.

1. Essential HTML5 Input Types

Text-Based Inputs

<!-- Email with built-in validation -->
<label for="email">Business Email*</label>
<input type="email" id="email" name="email" 
       required placeholder="[email protected]">

<!-- URL Input -->
<label for="website">Website URL</label>
<input type="url" id="website" name="website"
       pattern="https://.*" title="Include https://">

<!-- Search Field -->
<label for="search">Site Search</label>
<input type="search" id="search" name="q"
       aria-label="Search through site content">
Enter fullscreen mode Exit fullscreen mode

Numeric Inputs

<!-- Number Input -->
<label for="quantity">Quantity (1-10)</label>
<input type="number" id="quantity" name="quantity"
       min="1" max="10" step="1" value="1">

<!-- Range Slider -->
<label for="volume">Volume Control</label>
<input type="range" id="volume" name="volume"
       min="0" max="100" step="5" value="50">
Enter fullscreen mode Exit fullscreen mode

Temporal Inputs

<!-- Date Picker -->
<label for="birthdate">Birth Date</label>
<input type="date" id="birthdate" name="birthdate"
       min="1900-01-01" max="2023-12-31">

<!-- Time Input -->
<label for="appt">Meeting Time</label>
<input type="time" id="appt" name="appt"
       min="09:00" max="18:00" required>
Enter fullscreen mode Exit fullscreen mode

2. Professional Validation Patterns

Built-in Validation Attributes

<!-- Required Field -->
<input type="text" required aria-required="true">

<!-- Minimum Length -->
<input type="password" minlength="8" required>

<!-- Pattern Matching -->
<input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
       title="Format: 123-456-7890">

<!-- Custom Validation Message -->
<input type="email" oninvalid="this.setCustomValidity('Please enter a valid company email')">
Enter fullscreen mode Exit fullscreen mode

Constraint Validation API (JavaScript)

// Access validation state
const emailInput = document.getElementById('email');
if (!emailInput.checkValidity()) {
  console.log(emailInput.validationMessage);
}

// Custom validation
passwordInput.addEventListener('input', () => {
  const hasNumber = /\d/.test(passwordInput.value);
  passwordInput.setCustomValidity(
    hasNumber ? '' : 'Password must contain a number'
  );
});
Enter fullscreen mode Exit fullscreen mode

3. Complete Validation Form Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Professional Registration Form</title>
  <style>
    :root {
      --error: #d32f2f;
      --success: #388e3c;
    }

    .form-group {
      margin-bottom: 1.5rem;
    }

    input:invalid {
      border-color: var(--error);
    }

    input:valid {
      border-color: var(--success);
    }

    .error-message {
      color: var(--error);
      font-size: 0.875rem;
      margin-top: 0.25rem;
      display: none;
    }

    input:invalid + .error-message {
      display: block;
    }
  </style>
</head>
<body>
  <form id="registration" novalidate>
    <div class="form-group">
      <label for="fullname">Full Name*</label>
      <input type="text" id="fullname" name="fullname" 
             required minlength="2" maxlength="100">
      <div class="error-message">Please enter your full name</div>
    </div>

    <div class="form-group">
      <label for="company-email">Company Email*</label>
      <input type="email" id="company-email" name="email"
             required pattern=".+@company\.com$"
             title="Please use your company email">
      <div class="error-message">Valid company email required</div>
    </div>

    <div class="form-group">
      <label for="password">Password*</label>
      <input type="password" id="password" name="password"
             required minlength="8" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
             title="8+ chars with uppercase, lowercase & number">
      <div class="error-message">Password requirements not met</div>
    </div>

    <div class="form-group">
      <label for="start-date">Start Date*</label>
      <input type="date" id="start-date" name="startDate"
             required min="2023-01-01">
      <div class="error-message">Select a valid start date</div>
    </div>

    <button type="submit">Register Account</button>
  </form>

  <script>
    document.getElementById('registration').addEventListener('submit', (e) => {
      if (!e.target.checkValidity()) {
        e.preventDefault();
        // Show custom error messages
        Array.from(e.target.elements).forEach(el => {
          if (!el.checkValidity()) {
            el.nextElementSibling.textContent = 
              el.validationMessage || 'Invalid value';
          }
        });
      }
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Professional Validation Practices

  1. Progressive Enhancement Strategy

    • Start with HTML5 validation
    • Enhance with JavaScript for complex rules
    • Provide server-side validation as backup
  2. Accessibility Requirements

    • Associate error messages with inputs using aria-describedby
    • Ensure color contrast meets WCAG 2.1 AA
    • Support keyboard navigation through errors
  3. UX Best Practices

    • Validate on blur (after user leaves field)
    • Show success states for valid inputs
    • Position error messages consistently
    • Avoid alert() for error messages

Exercises

  1. Build a Credit Card Form with:

    • Number input (16 digits)
    • Expiry date (MM/YY format)
    • CVV (3-4 digits)
    • Real-time validation feedback
  2. Create a Survey Form with:

    • Required email validation
    • Age range (18-99) number input
    • Satisfaction scale (1-5 stars)
    • Custom validation messages
  3. Debug These Validation Issues:

   <input type="number" min="0" max="10">
   <span>Value must be between 0-10</span>
Enter fullscreen mode Exit fullscreen mode

What's Next?

Tomorrow (Day 16) covers Advanced Form Techniques including custom form controls, file uploads, and multi-step forms. For complete validation strategies and patterns, see Chapter 11 in the Learn Frontend Development in 180 Days ebook.

Pro Tip: Use the Constraint Validation API to customize the validation bubble appearance:

// Prevent default bubble
input.addEventListener('invalid', (e) => {
  e.preventDefault();
  // Show custom error UI
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)