Chapter 13: HTML Advanced Forms (Validation & Input Types)
13.1 Introduction to HTML Forms
Forms allow users to enter data and submit it to a server. HTML provides various input types and validation features to improve usability.
13.2 Input Types in HTML
HTML5 introduced several new input types to enhance the user experience.
Common Input Types:
text– Standard text inputemail– Requires a valid email formatpassword– Hides user inputnumber– Accepts only numberstel– For phone numbersdate– Date selectioncolor– Color pickerrange– Slider input
Example of Various Input Types:
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<label for="number">Enter a number:</label>
<input type="number" id="number" min="1" max="100">
<label for="date">Select a date:</label>
<input type="date" id="date">
<label for="color">Choose a color:</label>
<input type="color" id="color">
<input type="submit" value="Submit">
</form>
13.3 HTML Form Validation
Validation ensures that users enter data correctly before submission. HTML provides built-in validation attributes.
Validation Attributes:
required– Ensures the field is filledmin/max– Restricts numerical valuesminlength/maxlength– Limits text lengthpattern– Uses regex for custom validationstep– Defines numeric input increments
Example of Form Validation:
<form>
<label for="username">Username (min 5 chars):</label>
<input type="text" id="username" minlength="5" required>
<label for="password">Password (min 8 chars):</label>
<input type="password" id="password" minlength="8" required>
<label for="phone">Phone Number (10 digits):</label>
<input type="tel" id="phone" pattern="[0-9]{10}" required>
<input type="submit" value="Register">
</form>
13.4 Custom Validation Using JavaScript
Sometimes, additional validation is required beyond HTML's built-in validation.
Example of JavaScript Form Validation:
<script>
function validateForm() {
let email = document.getElementById("email").value;
if (!email.includes("@")) {
alert("Invalid email address!");
return false;
}
return true;
}
</script>
<form onsubmit="return validateForm()">
<input type="email" id="email" required>
<input type="submit" value="Submit">
</form>
13.5 File Uploads in Forms
The file input type allows users to upload files.
Example:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label for="file">Upload a file:</label>
<input type="file" id="file" name="file" required>
<input type="submit" value="Upload">
</form>
13.6 Summary
In this chapter, we covered:
- Different HTML input types
- Built-in form validation attributes
- Custom validation with JavaScript
- Handling file uploads