1KB Vue
JavaScript form validation
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:
HTML Form
<!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>
JavaScript Validation
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();
}
});
Explanation
-
HTML Form:
- Contains fields for name and email.
<span>elements are used to display error messages.
-
JavaScript:
- Adds an event listener to the form that listens for the
submitevent. - Clears any previous error messages.
- Validates the name field to ensure it's not empty.
- Validates the email field using a regular expression pattern to ensure it has the correct format.
- If validation fails, it prevents the form from being submitted by calling
event.preventDefault().
- Adds an event listener to the form that listens for the
You can expand this example by adding more fields and validations as needed.