Exercise 5: Basic Form Validation
HTML (index.html):
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<link rel=”stylesheet” href=”styles.css”>
<title>Form Validation</title>
</head>
<body>
<div class=”form-container”>
<form onsubmit=”validateForm(); return false;”>
<label for=”username”>Username:</label>
<input type=”text” id=”username” required>
<br>
<label for=”password”>Password:</label>
<input type=”password” id=”password” required>
<br>
<button type=”submit”>Submit</button>
</form>
<p id=”errorMessage” class=”error-message”></p>
</div>
<script src=”script.js”></script>
</body>
</html>
CSS (styles.css):
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.form-container {
text-align: center;
}
label {
display: block;
margin-top: 10px;
}
input {
padding: 10px;
font-size: 16px;
margin-bottom: 10px;
}
button {
padding: 10px;
font-size: 16px;
}
.error-message {
color: red;
font-weight: bold;
}
JavaScript (script.js):
function validateForm() {
const username = document.getElementById(‘username’).value;
const password = document.getElementById(‘password’).value;
const errorMessageElement = document.getElementById(‘errorMessage’);
if (username === ” || password === ”) {
errorMessageElement.textContent = ‘Both username and password are required.’;
} else if (password.length < 6) {
errorMessageElement.textContent = ‘Password must be at least 6 characters long.’;
} else {
errorMessageElement.textContent = ”;
alert(‘Form submitted successfully!’);
}
}
Explanation:
- The HTML file contains a simple form with username, password, and a submit button.
- The CSS file provides styling for the form elements.
- The JavaScript file includes a function (validateForm) to perform basic form validation, checking for non-empty fields and a minimum password length of 6 characters. The validation result is displayed in an error message element.