Bootstrap 5 Form Validation: Password Input with JavaScript
This is a Bootstrap 5 form with a password input field and a submit button, incorporating basic JavaScript validation. The password must be non-empty and exactly 6 characters long.
<!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>
The form utilizes Bootstrap's built-in form components, including a password input field and a submit button. The JavaScript validation script dynamically adds and removes the is-invalid class to control the display of validation messages, providing helpful feedback to the user. Upon successful validation, the form is submitted as intended.
原文地址: https://www.cveoy.top/t/topic/nnj8 著作权归作者所有。请勿转载和采集!