Introduction to Computer Science
Computer |
2025-03-05 15:33:46
JavaScript form validation is a technique used to ensure that the data submitted in a form is correct and complete before it is sent to the server. Here's a basic example of how you can implement form validation using JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
.error {
color: red;
font-size: 0.875em;
}
</style>
</head>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<span class="error" id="nameError"></span><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<span class="error" id="emailError"></span><br><br>
<input type="submit" value="Submit">
</form>
<script src="form-validation.js"></script>
</body>
</html>
Create a file named form-validation.js
with the following code:
document.getElementById('myForm').addEventListener('submit', function(event) {
let isValid = true;
// Clear previous errors
document.getElementById('nameError').textContent = '';
document.getElementById('emailError').textContent = '';
// Validate Name
const name = document.getElementById('name').value;
if (name.trim() === '') {
document.getElementById('nameError').textContent = 'Name is required';
isValid = false;
}
// Validate Email
const email = document.getElementById('email').value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
document.getElementById('emailError').textContent = 'Invalid email format';
isValid = false;
}
// If form is invalid, prevent submission
if (!isValid) {
event.preventDefault();
}
});
HTML Form:
<span>
elements are used to display error messages.JavaScript:
submit
event.event.preventDefault()
.You can expand this example by adding more fields and validations as needed.