Bootstrap - Validation: A Comprehensive Guide for Beginners
Hello there, aspiring web developers! Today, we're going to dive into the world of Bootstrap validation. As your friendly neighborhood computer teacher, I'm excited to guide you through this journey. Don't worry if you're new to programming – we'll start from the basics and work our way up. By the end of this tutorial, you'll be validating forms like a pro!
What is Bootstrap Validation?
Before we jump into the nitty-gritty, let's understand what Bootstrap validation is all about. Imagine you're filling out a form online, and you accidentally leave a required field empty. Suddenly, the form highlights that field in red, telling you to fill it out. That's form validation in action! Bootstrap, our trusty front-end toolkit, provides us with built-in validation features to make this process smooth and user-friendly.
Custom Styles
Let's start with custom styles for our form validation. Bootstrap allows us to add our own flair to the validation process. Here's a simple example:
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
In this example, we've added the needs-validation
class to our form and set novalidate
to prevent default browser validation. The required
attribute on the input field tells Bootstrap that this field must be filled out.
Now, let's add some JavaScript to make it work:
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
This JavaScript code adds event listeners to our form, checking for validity when the form is submitted. If the form is invalid, it prevents submission and adds the was-validated
class, which triggers our custom styles.
Browser Defaults
Sometimes, you might want to use the browser's default validation styles. It's like letting the browser do the heavy lifting for you! Here's how you can do that:
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" required>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
In this case, we've removed the needs-validation
class and the novalidate
attribute. The browser will now handle validation using its default styles.
Server-Side Validation
While client-side validation is great for user experience, we should always implement server-side validation for security. Here's a simple PHP example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This PHP code checks if the submitted email is valid. Always remember: never trust user input!
Supported Elements
Bootstrap validation supports various form elements. Let's look at a few:
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" required>
</div>
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country" required>
<option value="">Choose...</option>
<option>USA</option>
<option>UK</option>
<option>Canada</option>
</select>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="terms" required>
<label class="form-check-label" for="terms">
Agree to terms and conditions
</label>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
This form includes text input, password input, select dropdown, and checkbox - all supported by Bootstrap validation.
Tooltips
Want to add some extra pizzazz to your validation messages? Try tooltips! Here's how:
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" required>
<div class="invalid-tooltip">
Please choose a unique username.
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
We've replaced invalid-feedback
with invalid-tooltip
. Now, instead of text below the input, you'll see a fancy tooltip!
Validation Methods
Here's a table of common validation methods you can use:
Method | Description |
---|---|
required |
Field cannot be empty |
minlength |
Minimum length of characters |
maxlength |
Maximum length of characters |
min |
Minimum value for numeric inputs |
max |
Maximum value for numeric inputs |
type="email" |
Must be a valid email address |
pattern |
Must match a specific pattern |
Remember, you can combine these methods for more complex validation rules!
And there you have it, folks! We've covered the basics of Bootstrap validation, from custom styles to tooltips. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Happy coding, and may your forms always be validated!
Credits: Image by storyset