BootStrap4登录表单验证示例
首先是效果图,如下
实现:
在input元素后加上校验的信息反馈,示例如下:
<input type="password" class="form-control" pattern="[A-Za-z0-9]{6,30}" required>
<div class="invalid-feedback">密码长度至少为六位,只能是大小写字母或数字!</div>
<input type="email" class="form-control" required>
<div class="invalid-feedback">请输入正确格式的邮箱</div>
然后使用JQuery或者JS在触发表单提交事件的时候,检查表单是否合法。若不合法,给form元素添加上“was-validated”类,并阻止表单的提交。(给form元素加上“was-validated”类之后就会显示表单校验成功或失败的样式了)
注意使用BootStrap4的表单验证需要给form元素添加novalidate,以此屏蔽浏览器的默认表单检查(浏览器默认的表单检查会覆盖掉BootStrap4的表单检查效果)。
此外,BootStrap的验证样式还有另外一种效果,如下图
官方文档
Code
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$("form").submit(function (event) {
if ($(this)[0].checkValidity() === false) {
event.preventDefault();// 阻止提交表单
event.stopPropagation();
}
$(this).addClass("was-validated");
});
})
</script>
</head>
<body>
<div class="container">
<form novalidate>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" required>
<div class="invalid-feedback">请输入正确格式的邮箱</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" pattern="[A-Za-z0-9]{6,30}" required>
<div class="invalid-feedback">密码长度至少为六位,只能是大小写字母或数字!</div>
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Radio</legend>
<div class="col-sm-10">
<div class="form-check">
<input type="radio" class="form-check-input" name="radio" required>
<label class="form-check-label">radio1</label>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" name="radio">
<label class="form-check-label">radio2</label>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" name="radio" disabled>
<label class="form-check-label">radio3</label>
</div>
</div>
</div>
</fieldset>
<div class="form-group row">
<label class="col-sm-2 col-form-label pt-0">Checkbox</label>
<div class="col-sm-10">
<div class="form-check">
<input type="checkbox" class="form-check-input" required>
<label class="form-check-label">Example checkbox</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col">
<button class="btn btn-primary">Sign in</button>
</div>
</div>
</form>
</div>
</body>
</html>