JavaScript form validation
Posté 2025-02-03 17:37:05
0
692

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
submit
event. - 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.
Rechercher
Sellect from all Catégories bellow ⇓
- Artificial Intelligence (AI)
- Cybersecurity
- Blockchain & Cryptocurrencies
- Internet of Things
- Cloud Computing
- Big Data & Analytics
- Virtual Reality
- 5G & Future Connectivity
- Robotics & Automation
- Software Development & Programming
- Tech Hardware & Devices
- Tech in Healthcare
- Tech in Business
- Gaming Technologies
- Tech in Education
- Machine Learning (ML)
- Blogging
- Affiliate Marketing
- Make Money
- Digital Marketing
- Product Review
- Social Media
- Excel
- Graphics design
- Freelancing/Consulting
- FinTech (Financial Technology)
- E-commerce and Digital Marketing
- Business
- Sport
- Self Development
- Tips to Success
- Video Editing
- Photo Editing
- Website Promotion
- YouTube
- Lifestyle
- Health
- Computer
- Téléphone
- Music
- Accounting
- Causes
- Networking
Lire la suite
How to Build a Clean Online Portfolio Using PHP
Building a clean online portfolio requires...
Introduction To HTML
HTML (HyperText Markup Language) is the...
How to Make Money Through E-commerce & Selling Products
Here’s a comprehensive guide on how to...
Steps On How To Start a Business Without a Physical Shop or a Website
Starting a business without a physical shop or...
How Build a mindset for wealth
Building a mindset for wealth requires...