Creating a simple contact form using HTML, CSS, and JavaScript involves structuring the form with HTML, styling it with CSS, and adding interactivity and validation with JavaScript. Here’s a step-by-step guide to help you build a functional contact form.
🧱 1. HTML: Structure the Form
Begin by setting up the basic structure of your contact form using HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Contact Form</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="contact-form-container">
<h2>Contact Us</h2>
<form id="contactForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="Your Name" required />
<span class="error-message" id="nameError"></span>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Your Email" required />
<span class="error-message" id="emailError"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" name="message" placeholder="Your Message" required></textarea>
<span class="error-message" id="messageError"></span>
</div>
<button type="submit">Submit</button>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
This structure includes input fields for the user’s name, email, and message, along with corresponding labels and placeholders. Each input has an associated span element to display error messages during validation.
🎨 2. CSS: Style the Form
Next, style your form to enhance its appearance and usability.
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
}
.contact-form-container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
max-width: 500px;
margin: auto;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="email"],
textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.error-message {
color: red;
font-size: 0.9em;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
This CSS centers the form on the page, styles the input fields and buttons, and defines the appearance of error messages.
🧠 3. JavaScript: Add Validation
Implement client-side validation to ensure that users provide the necessary information before submitting the form.
// script.js
document.getElementById('contactForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
// Clear previous error messages
document.getElementById('nameError').textContent = '';
document.getElementById('emailError').textContent = '';
document.getElementById('messageError').textContent = '';
// Get form values
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const message = document.getElementById('message').value.trim();
let isValid = true;
// Validate name
if (name.length < 5) {
document.getElementById('nameError').textContent = 'Name must be at least 5 characters.';
isValid = false;
}
// Validate email
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(emailPattern)) {
document.getElementById('emailError').textContent = 'Please enter a valid email address.';
isValid = false;
}
// Validate message
if (message.length < 10) {
document.getElementById('messageError').textContent = 'Message must be at least 10 characters.';
isValid = false;
}
if (isValid) {
// Here you can add code to send the form data to the server
alert('Form submitted successfully!');
// Reset the form
document.getElementById('contactForm').reset();
}
});
This script adds an event listener to the form’s submit event, prevents the default submission behavior, and performs validation checks on the input fields. If all validations pass, it displays a success message and resets the form.
📬 4. Handling Form Submission
To process the form data and send it via email, you’ll need to implement server-side functionality, as JavaScript alone cannot send emails. One common approach is to use a server-side language like PHP to handle the form submission.
Here’s a basic example of how you might handle the form submission using PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
$to = "your-email@example.com";
$subject = "New Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage:\n$message";
$headers = "From: $email";
if (mail($to, $subject, $body, $headers)) {
echo "Message sent successfully!";
} else {
echo "Failed to send message.";
}
}
?>
Save this code in a file named sendmail.php
and set your form’s action
attribute to point to this file. Ensure your server supports PHP and is configured to send emails.
📚 Additional Resources
For more detailed tutorials and examples, consider exploring the following resources:
- W3Schools: How To Create a Contact Form with CSS
- GeeksforGeeks: Create a Contact Form using HTML CSS & JavaScript
- Mailtrap Blog: JavaScript Contact Form Tutorial
These resources provide comprehensive guides and code examples to help you build and enhance your contact form.
By following these steps, you can create a functional and user-friendly contact form for your website.