Menu
Bootstrap 5 Form Validation
Form Validation
You can use different validation classes to provide valuable feedback to users. Add either .was-validated or .needs-validation to the <form> element, depending on whether you want to provide validation feedback before or after submitting the form. The input fields will have a green (valid) or red (invalid) border to indicate what’s missing in the form. You can also add a .valid-feedback or .invalid-feedback message to tell the user explicitly what’s missing, or needs to be done before submitting the form.
Example
In this example, we use .was-validated to indicate what’s missing before submitting the form:
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Bootstrap Example</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css” rel=”stylesheet”>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js”></script>
</head>
<body>
<div>
<h3>Form Validation</h3>
<p>Try to submit the form.</p>
<form action=”/action_page.php”>
<div>
<label for=”uname”>Username:</label>
<input type=”text” id=”uname” placeholder=”Enter username” name=”uname” required>
<div>Valid.</div>
<div>Please fill out this field.</div>
</div>
<div>
<label for=”pwd”>Password:</label>
<input type=”password” id=”pwd” placeholder=”Enter password” name=”pswd” required>
<div>Valid.</div>
<div>Please fill out this field.</div>
</div>
<div>
<input type=”checkbox” id=”myCheck” name=”remember” required>
<label for=”myCheck”>I agree on blabla.</label>
<div>Valid.</div>
<div>Check this checkbox to continue.</div>
</div>
<button type=”submit”>Submit</button>
</form>
</div>
</body>
</html>