Lesson 22: Form Validation & Error Handling

📌 Objective: Learn how to implement form validation and handle errors using Bootstrap’s built-in validation system and JavaScript.


🔹 1. Introduction to Form Validation & Error Handling

Form validation ensures that users enter valid data before submission.

💡 Why Use Form Validation?
✔️ Prevents incorrect data submission.
✔️ Enhances user experience with instant feedback.
✔️ Bootstrap provides built-in styles for validation.


🔹 2. Bootstrap’s Built-in Form Validation

Bootstrap uses CSS classes to indicate form validation states.

Example: Basic Validation with .is-invalid & .is-valid

html
<form>
<div class="mb-3">
<label class="form-label">Email</label>
<input type="email" class="form-control is-invalid" placeholder="Enter your email">
<div class="invalid-feedback">Please enter a valid email.</div>
</div>

<div class="mb-3">
<label class="form-label">Username</label>
<input type="text" class="form-control is-valid" placeholder="Valid username">
<div class="valid-feedback">Looks good!</div>
</div>

<button type="submit" class="btn btn-primary">Submit</button>
</form>

🔹 What happens?

  • Red input field (is-invalid) appears for incorrect input.
  • Green input field (is-valid) appears for correct input.

🔹 3. Adding JavaScript-Powered Validation

Bootstrap’s validation system works with JavaScript.

Example: JavaScript-Powered Validation

html
<form class="needs-validation" novalidate>
<div class="mb-3">
<label class="form-label">Email</label>
<input type="email" class="form-control" required>
<div class="invalid-feedback">Please enter a valid email.</div>
</div>

<div class="mb-3">
<label class="form-label">Password</label>
<input type="password" class="form-control" required>
<div class="invalid-feedback">Password is required.</div>
</div>

<button type="submit" class="btn btn-success">Submit</button>
</form>

<script>
document.querySelector("form").addEventListener("submit", function(event) {
if (!this.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
this.classList.add("was-validated");
});
</script>

🔹 What happens?

  • Invalid fields show an error message (invalid-feedback).
  • If fields are valid, the form submits.

🔹 4. Customizing Error Messages

You can customize validation messages for better UX.

Example: Custom Validation Messages

html
<form class="needs-validation" novalidate>
<div class="mb-3">
<label class="form-label">Username</label>
<input type="text" class="form-control" id="username" required>
<div class="invalid-feedback">Username cannot be empty!</div>
</div>

<button type="submit" class="btn btn-danger">Submit</button>
</form>

<script>
document.querySelector("form").addEventListener("submit", function(event) {
let username = document.getElementById("username");
if (username.value.trim() === "") {
username.classList.add("is-invalid");
event.preventDefault();
} else {
username.classList.remove("is-invalid");
}
});
</script>

🔹 What happens?

  • The error message appears if the username field is empty.

🔹 5. Adding Regex Pattern Validation

Use regex patterns to enforce specific input formats.

Example: Phone Number Validation

html
<form>
<div class="mb-3">
<label class="form-label">Phone Number</label>
<input type="tel" class="form-control" id="phone" pattern="[0-9]{10}" required>
<div class="invalid-feedback">Please enter a 10-digit phone number.</div>
</div>

<button type="submit" class="btn btn-info">Submit</button>
</form>

🔹 What happens?

  • Only 10-digit numbers are accepted.

🔹 6. Displaying Real-Time Validation Messages

Example: Live Validation Feedback

html
<form>
<div class="mb-3">
<label class="form-label">Email</label>
<input type="email" class="form-control" id="liveEmail" required>
<div class="invalid-feedback">Invalid email format.</div>
</div>
</form>

<script>
document.getElementById("liveEmail").addEventListener("input", function () {
if (this.checkValidity()) {
this.classList.remove("is-invalid");
this.classList.add("is-valid");
} else {
this.classList.remove("is-valid");
this.classList.add("is-invalid");
}
});
</script>

🔹 What happens?

  • The input turns green (is-valid) when correct and red (is-invalid) when incorrect.

🔹 7. Adding Password Strength Validation

Password validation ensures secure passwords.

Example: Password Strength Indicator

html
<form>
<div class="mb-3">
<label class="form-label">Password</label>
<input type="password" class="form-control" id="password" required>
<small id="passwordHelp" class="form-text">Must be 8+ characters, include numbers & symbols.</small>
<div class="invalid-feedback">Weak password.</div>
</div>
</form>

<script>
document.getElementById("password").addEventListener("input", function () {
let password = this.value;
let regex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;

if (regex.test(password)) {
this.classList.add("is-valid");
this.classList.remove("is-invalid");
} else {
this.classList.add("is-invalid");
this.classList.remove("is-valid");
}
});
</script>

🔹 What happens?

  • Green input when password meets criteria.
  • Red input when password is weak.

🔹 8. Handling Server-Side Validation Errors

Sometimes validation errors come from the backend.

Example: Displaying Server Errors

html
<form>
<div class="mb-3">
<label class="form-label">Email</label>
<input type="email" class="form-control is-invalid">
<div class="invalid-feedback">This email is already taken.</div>
</div>
</form>

🔹 What happens?

  • Server response triggers an error message.

📝 Lesson Recap Quiz

🎯 Test your knowledge of Bootstrap Form Validation.

📌 Multiple-Choice Questions (MCQs)

1️⃣ What class highlights invalid fields in Bootstrap?
a) .error-input
b) .invalid
c) .is-invalid
d) .form-error

Correct Answer: c) .is-invalid


2️⃣ What Bootstrap class enables real-time validation?
a) .form-live
b) .needs-validation
c) .input-validation
d) .validate-now

Correct Answer: b) .needs-validation


📌 True or False

3️⃣ Bootstrap validation works without JavaScript.
Answer: False

4️⃣ Password strength validation can be done using Regex.
Answer: True


🎯 Practical Challenge

✅ Implement live email validation using .is-invalid and .is-valid.
✅ Create a signup form with password strength validation.
✅ Display server-side validation errors for a taken email.
✅ Post your solution in the discussion forum for feedback!


🎓 Lesson Summary

Bootstrap validation (is-invalid, is-valid) highlights form errors.
JavaScript validation (checkValidity()) prevents incorrect submissions.
Regex patterns (pattern="...") enforce correct input formats.
Server-side validation errors can be displayed with .invalid-feedback.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *