Bootstrap5 表单验证

我们可以使用不同的验证类来设置表单的验证功能。

.was-validated.needs-validation 添加到 <form> 元素中,input 输入字段将具有绿色(有效)或红色(无效)边框效果,用于说明表单是否需要输入内容。

.valid-feedback.invalid-feedback 类用来告诉用户缺少什么信息,或者在提交表单之前需要完成什么。

使用 .was-validated 类显示表单在提交之前需要填写的内容:

<form action="" class="was-validated"> <div class="form-group"> <label for="uname">Username:</label> <input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname" required> <div class="valid-feedback">验证成功!</div> <div class="invalid-feedback">请输入用户名!</div> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd" required> <div class="valid-feedback">验证成功!</div> <div class="invalid-feedback">请输入密码!</div> </div> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember" required> 同意协议 <div class="valid-feedback">验证成功!</div> <div class="invalid-feedback">同意协议才能提交。</div> </label> </div> <button type="submit" class="btn btn-primary">提交</button> </form>

使用 .needs-validation,它将在表单提交之后验证缺少的内容。这里需要添加一些 JavaScript 代码才能使代码正常工作:

<form action="" class="needs-validation" novalidate> <div class="form-group"> <label for="uname">Username:</label> <input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname" required> <div class="valid-feedback">验证成功!</div> <div class="invalid-feedback">请输入用户名!</div> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd" required> <div class="valid-feedback">验证成功!</div> <div class="invalid-feedback">请输入密码!</div> </div> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember" required> 同意协议 <div class="valid-feedback">验证成功!</div> <div class="invalid-feedback">同意协议才能提交。</div> </label> </div> <button type="submit" class="btn btn-primary">提交</button> </form> <script> // 如果验证不通过禁止提交表单 (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); })(); </script>