Form validation ensures that users enter correct and complete data before submitting a form. It improves user experience and prevents incorrect data from being stored in databases. There are two main types of form validation:
- Client-Side Validation (using HTML5 or JavaScript)
- Server-Side Validation (handled by the backend for security)
Client-side validation is the first line of defense, ensuring users correct their input before submission. However, it should not replace server-side validation, as users can bypass client-side checks.
HTML5 plays a key role in building modern websites and web apps. You can learn HTML5 on YouTube or enroll in a full web development course. The course should deal with markup languages and programs like React and Javascript.
1. HTML5 Built-in Validation
HTML5 introduced new input types and attributes that provide easy form validation without JavaScript. This helps prevent invalid input at the browser level.
1.1 HTML5 Form Validation Attributes
Here are some commonly used HTML5 validation attributes:
Attribute | Description |
required | Makes the field mandatory |
minlength and maxlength | Restricts input length |
min and max | Limits numerical values |
type=”email” | Ensures a valid email format |
type=”url” | Ensures a valid URL format |
type=”number” | Accepts only numerical values |
pattern=”[A-Za-z]{3,}” | Uses regex to validate custom patterns |
step=”any” | Allows decimal numbers |
1.2 Example of HTML5 Form Validation
Here is a simple form using HTML5 validation:
<form action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="age">Age (between 18-60):</label>
<input type="number" id="age" name="age" min="18" max="60" required>
<label for="password">Password (min 6 characters):</label>
<input type="password" id="password" name="password" minlength="6" required>
<label for="website">Website:</label>
<input type="url" id="website" name="website">
<button type="submit">Submit</button>
</form>
How it Works:
- If the name field is left empty, the form will not submit.
- The email field will only accept valid email addresses.
- The age field restricts input to values between 18 and 60.
- The password must be at least 6 characters long.
- The website field will only accept a valid URL.
2. JavaScript Form Validation
HTML5 validation is useful but limited. JavaScript provides more control over validation and can offer real-time feedback before form submission.
2.1 JavaScript Form Validation Example
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<small id="error" style="color: red;"></small>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
let username = document.getElementById("username").value;
let error = document.getElementById("error");
if (username.length < 3) {
error.textContent = "Username must be at least 3 characters!";
event.preventDefault(); // Prevent form submission
} else {
error.textContent = "";
}
});
</script>
How it Works:
- When the form is submitted, JavaScript checks if the username is less than 3 characters.
- If invalid, an error message is displayed, and the form submission is prevented.
- If valid, the error message is cleared, and the form submits successfully.
3. Bootstrap Form Validation
If you’re using Bootstrap, you can take advantage of its built-in validation classes.
3.1 Example of Bootstrap
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" required>
<div class="invalid-feedback">Please enter your first name.</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<script>
(function () {
'use strict';
document.querySelector('.needs-validation').addEventListener('submit', function (event) {
if (!this.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
this.classList.add('was-validated');
}, false);
})();
</script>
How it Works:
- The form uses Bootstrap’s needs-validation class.
- The novalidate attribute disables default browser validation.
- JavaScript adds .was-validated to show validation styles.
- invalid-feedback provides user-friendly error messages.
4. Regular Expressions (Regex) for Advanced Validation
For more complex validation, you can use regular expressions (regex).
4.1 Example of Regex Validation in JavaScript
<form id="regexForm">
<label for="phone">Phone Number (Format: 123-456-7890):</label>
<input type="text" id="phone" name="phone">
<small id="phoneError" style="color: red;"></small>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("regexForm").addEventListener("submit", function(event) {
let phone = document.getElementById("phone").value;
let phoneError = document.getElementById("phoneError");
let phonePattern = /^\d{3}-\d{3}-\d{4}$/;
if (!phonePattern.test(phone)) {
phoneError.textContent = "Invalid phone number format!";
event.preventDefault();
} else {
phoneError.textContent = "";
}
});
</script>
How it Works:
- The regex pattern ^\d{3}-\d{3}-\d{4}$ ensures a valid phone number format.
- If the input doesn’t match, an error message appears.
- The form will not submit until the correct format is used.
5. Best Practices for Form Validation
Use HTML5 validation for basic checks (e.g., required fields, email format).
Use JavaScript validation for real-time feedback and custom rules.
Always validate on the server to prevent security risks.
Use regex for complex validation (e.g., phone numbers, postal codes).
Provide user-friendly error messages and real-time feedback.
Prevent form submission when invalid data is entered.
6. Summary
Method | Pros | Cons |
HTML5 Validation | Simple, no extra code, built-in support | Limited customization |
JavaScript Validation | More control, real-time feedback | Can be bypassed by disabling JS |
Server-Side Validation | Secure, ensures data integrity | Requires backend implementation |
Regex Validation | Powerful pattern matching | Can be complex for beginners |
Which One Should You Use?
- Use HTML5 validation for quick checks.
- Use JavaScript for dynamic validation and better UX.
- Always use server-side validation to ensure security.