MSC(CS) FSD-1 Practical 3- Email validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
<script>
// ES6 function to validate form fields
const validateForm = () => {
let isValid = true;
// Get input values
const email = document.getElementById('email').value.trim();
// Get error element
const emailError = document.getElementById('emailError');
// Reset error message
emailError.textContent = '';
// Regular Expression for validating email
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
// Validate email
if (!email || !emailRegex.test(email)) {
emailError.textContent = 'Please enter a valid email address.';
isValid = false;
}
// If the form is valid, show success message
if (isValid) {
alert('Login Successful!');
document.getElementById('loginForm').reset(); // Clear the form
}
};
</script>
</head>
<body>
<h2>Login Form</h2>
<form id="loginForm">
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email">
<span id="emailError" style="color:red;"></span>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" placeholder="Enter your password">
<br><br>
<button type="button" onclick="validateForm()">Login</button>
</form>
</body>
</html>
Comments
Post a Comment