Bootstrap 5 表单验证
Bootstrap 2023-08-10 09:26:56小码哥的IT人生shichen
Bootstrap 5 表单验证
表单验证
您可以使用不同的验证类向用户提供有价值的反馈。请将 .was-validated
或 .needs-validation
添加到 <form> 元素,具体取决于您是要在提交表单之前还是之后提供验证反馈。输入字段将会有绿色(有效)或红色(无效)边框,以指示表单中缺少的内容。您还可以添加 .valid-feedback
或 .invalid-feedback
消息,以明确告知用户缺失了什么,或者在提交表单之前需要完成什么。
示例代码:
在这个例子中,我们在提交表单之前使用 .was-validated
来指示缺少什么:
<form action="/action_page.php" class="was-validated">
<div class="mb-3 mt-3">
<label for="uname" class="form-label">用户名:</label>
<input type="text" class="form-control" id="uname" placeholder="请输入用户名" name="uname" required>
<div class="valid-feedback">有效的。</div>
<div class="invalid-feedback">请填写此字段。</div>
</div>
<div class="mb-3">
<label for="pwd" class="form-label">密码:</label>
<input type="password" class="form-control" id="pwd" placeholder="请输入密码" name="pswd" required>
<div class="valid-feedback">有效的。</div>
<div class="invalid-feedback">请填写此字段。</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" id="myCheck" name="remember" required>
<label class="form-check-label" for="myCheck">我同意这些条款。</label>
<div class="valid-feedback">有效的。</div>
<div class="invalid-feedback">选中此复选框以继续。</div>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
完整实例【亲自试一试】:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 实例</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h3>表单验证</h3>
<p>请尝试提交表单。</p>
<form action="/demo/demo_form.php" class="was-validated">
<div class="mb-3 mt-3">
<label for="uname" class="form-label">用户名:</label>
<input type="text" class="form-control" id="uname" placeholder="请输入用户名" name="uname" required>
<div class="valid-feedback">有效的。</div>
<div class="invalid-feedback">请填写此字段。</div>
</div>
<div class="mb-3">
<label for="pwd" class="form-label">密码:</label>
<input type="password" class="form-control" id="pwd" placeholder="请输入密码" name="pswd" required>
<div class="valid-feedback">有效的。</div>
<div class="invalid-feedback">请填写此字段。</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" id="myCheck" name="remember" required>
<label class="form-check-label" for="myCheck">我同意这些条款。</label>
<div class="valid-feedback">有效的。</div>
<div class="invalid-feedback">选中此复选框以继续。</div>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
</div>
</body>
</html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html