⬅ Previous Next ➡

19. HTML5 Form Validation

HTML5 Form Validation
  • HTML5 Validation: This allows the browser to check user data automatically without needing complex JavaScript. It improves user experience by giving instant feedback.
  • Core Validation Attributes:
    • required: Forces the user to fill out the field before the form can be submitted.
    • pattern: Uses a Regular Expression (RegEx) to match specific formats (like a specific phone number pattern).
    • min / max: Sets numeric limits for type="number" or date limits for type="date".
    • minlength / maxlength: Controls the number of characters allowed in text fields.
  • Automatic Type Validation:
    • type="email": Automatically checks for a valid email structure (contains @ and a domain).
    • type="url": Ensures the input starts with a protocol like http:// or https://.
  • The title Attribute:
    • When a validation fails, the text inside the title attribute is often shown as a tooltip to help the user understand the error.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML5 Form Validation Examples</title>
</head>

<body>

<h2>User Registration with HTML5 Validation</h2>

<form action="/submit_form.php" method="POST">

  <!-- Example 1: Required Text + Min/Max Length -->
  <label>Username (5-12 chars):</label><br>
  <input type="text" name="user" minlength="5" maxlength="12" required>
  <br><br>

  <!-- Example 2: Email Validation -->
  <label>Email Address:</label><br>
  <input type="email" name="email" required>
  <br><br>

  <!-- Example 3: Password with Pattern (At least 1 letter and 1 number, min 6) -->
  <label>Password (min 6, include letter + number):</label><br>
  <input type="password" name="pwd" minlength="6" pattern="(?=.*[A-Za-z])(?=.*[0-9]).{6,}" title="Must contain at least 1 letter, 1 number, and minimum 6 characters" required>
  <br><br>

  <!-- Example 4: Number Range Validation -->
  <label>Age (18 to 99):</label><br>
  <input type="number" name="age" min="18" max="99" required>
  <br><br>

  <!-- Example 5: Pattern Validation (10 Digit Mobile) -->
  <label>Mobile (10 digits):</label><br>
  <input type="text" name="phone" pattern="[0-9]{10}" title="Please enter exactly 10 digits" required>
  <br><br>

  <!-- Example 6: URL Validation -->
  <label>Website URL:</label><br>
  <input type="url" name="website" placeholder="https://example.com">
  <br><br>

  <!-- Example 7: Date Limits (After Jan 2026) -->
  <label>Appointment Date (After Jan 2026):</label><br>
  <input type="date" name="date" min="2026-01-01" required>
  <br><br>

  <!-- Example 8: Checkbox Required (Terms) -->
  <input type="checkbox" id="terms" name="terms" required>
  <label for="terms">I agree to the Terms and Conditions</label>
  <br><br>

  <!-- Submit Button -->
  <input type="submit" value="Submit Form">

</form>

</body>
</html>
⬅ Previous Next ➡