Contact form validation

HTML, CSS, and JavaScript contact form validation example

Ishrat
1 min readFeb 4, 2023

Here’s a simple example of how you can validate a contact form using HTML, CSS, and JavaScript:

HTML:

<form id="contact-form">
<label for="name">Name:</label><br>
<input type="text" id="name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" required><br>
<label for="message">Message:</label><br>
<textarea id="message" required></textarea><br>
<input type="submit" value="Submit">
</form>

CSS:

#contact-form {
width: 500px;
margin: 0 auto;
}

#contact-form label {
display: block;
margin-bottom: 5px;
}

#contact-form input, #contact-form textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
box-sizing: border-box;
}

JavaScript:

const form = document.getElementById('contact-form');

form.addEventListener('submit', (event) => {
event.preventDefault();

const name = form.elements.name.value;
const email = form.elements.email.value;
const message = form.elements.message.value;

if (name && email && message) {
// Form is valid, do something here (e.g. send form data to a server)
} else {
// Form is invalid, display an error message
}
});

This code will validate the form by ensuring that the name, email, and message fields are filled out before submission. If any of these fields are left empty, the form will not be submitted, and an error message can be displayed.

Happy coding!

--

--