Activity 11
Activity 11
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your name" minlength="2" required>
<span id="nameError" class="error"></span>
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email" required>
<span id="emailError" class="error"></span>
<label for="password">Password:</label>
<input type="password" id="password" placeholder="Enter your password" minlength="6" required>
<span id="passwordError" class="error"></span>
<button type="submit">Submit</button>
</form>
<script>
// Get references to the form and input fields
const form = document.querySelector('form');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
function validateName() {
// Check if name input is valid
if (nameInput.value.length < 2) {
nameInput.classList.add('error');
document.getElementById('nameError').textContent = "Name must be at least 2 characters.";
} else {
nameInput.classList.remove('error');
document.getElementById('nameError').textContent = "";
}
}
function validateEmail() {
// Check if email input is valid
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('error');
document.getElementById('emailError').textContent = "Please enter a valid email address.";
} else {
emailInput.classList.remove('error');
document.getElementById('emailError').textContent = "";
}
}
function validatePassword() {
// Check if password input is valid
if (passwordInput.value.length < 6) {
passwordInput.classList.add('error');
document.getElementById('passwordError').textContent = "Password must be at least 6 characters.";
} else {
passwordInput.classList.remove('error');
document.getElementById('passwordError').textContent = "";
}
}
// Add submit event listener to prevent form submission if any input is invalid
form.addEventListener('submit', function(event) {
if (!nameInput.checkValidity() || !emailInput.checkValidity() || !passwordInput.checkValidity()) {
event.preventDefault();
}
});
</script>
<style>
.error {
color: red;
}
</style>