基于bootstrap5 生成一个form表单表单要求有一个按钮一个密码输入框并用js做验证密码不能为空密码必须为6个字符
以下是一个基于Bootstrap 5的表单,包含了一个密码输入框和一个提交按钮,并附带了基本的验证功能,密码不能为空且必须为6个字符:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bootstrap 5 Form Validation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Form Validation</h1>
<form id="myForm" method="post">
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password">
<div id="passwordHelp" class="form-text">Password must be 6 characters long.</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script>
// Get the form element and add a submit event listener
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
// Prevent the default form submission
event.preventDefault();
// Get the password input field value
const password = document.getElementById('password').value;
// Validate the password
if (password.length === 0) {
// If password is empty
document.getElementById('password').classList.add('is-invalid'); // Add invalid class
document.getElementById('passwordHelp').innerHTML = 'Password is required.'; // Update help text
} else if (password.length !== 6) {
// If password is not 6 characters long
document.getElementById('password').classList.add('is-invalid'); // Add invalid class
document.getElementById('passwordHelp').innerHTML = 'Password must be 6 characters long.'; // Update help text
} else {
// If password is valid
document.getElementById('password').classList.remove('is-invalid'); // Remove invalid class
document.getElementById('passwordHelp').innerHTML = 'Password must be 6 characters long.'; // Restore help text
form.submit(); // Submit the form
}
});
</script>
</body>
</html>
在这个表单中,我们使用了Bootstrap的表单组件,包括一个密码输入框和一个提交按钮。我们还添加了一个表单验证的脚本,用于验证密码输入框的输入是否符合要求。这个脚本通过添加和删除is-invalid类来控制验证信息的显示和隐藏,同时更新帮助文本来提示用户输入要求。如果验证通过,表单将被正常提交。
原文地址: https://www.cveoy.top/t/topic/b3c0 著作权归作者所有。请勿转载和采集!