<section id="contact-us"> <div class="contact-form"> <center> <h2>Contact Us</h2> <form…
- User
- Assistant
To ensure that your contact form only accepts valid email addresses, you can add validation constraints using HTML5 attributes and JavaScript. Here's how you can modify your code to enforce email format validation:
HTML5 provides built-in validation for email input fields. You can enhance this by adding a pattern attribute to specify a regular expression that the email must match.
Modify your email input field as follows:
<input type="email" id="email" name="email" placeholder="Your Email" required
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
title="Please enter a valid email address">
Explanation:
pattern attribute: Specifies a regex pattern that the input value must match.title attribute: Provides a tooltip message when the input doesn't match the pattern.For additional validation and better control over user input, you can use JavaScript to validate the email format before the form is submitted.
Add the following script to your page:
<script>
document.getElementById('contactForm').addEventListener('submit', function(event) {
const emailInput = document.getElementById('email');
const email = emailInput.value.trim();
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email address.');
emailInput.focus();
event.preventDefault(); // Prevent form submission
}
});
</script>
Explanation:
emailPattern checks for a basic valid email structure.submit event to validate the email field.Here is your updated contact form with both HTML5 and JavaScript validation:
<section id="contact-us">
<div class="contact-form">
<center>
<h2>Contact Us</h2>
<form id="contactForm">
<p>Have questions or suggest changes? Reach out to our team, and we'll be happy to assist you.</p>
<input type="text" id="name" name="name" placeholder="Your Name" required>
<input type="email" id="email" name="email" placeholder="Your Email" required
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
title="Please enter a valid email address">
<textarea id="message" name="message" placeholder="Your Message" required></textarea>
<button type="submit">Send</button>
</form>
<div id="confirmationMessage" class="hidden">
<h3>Message has been sent!</h3>
</div>
</center>
</div>
</section>
<script>
document.getElementById('contactForm').addEventListener('submit', function(event) {
const emailInput = document.getElementById('email');
const email = emailInput.value.trim();
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email address.');
emailInput.focus();
event.preventDefault(); // Prevent form submission
}
});
</script>
<style>
input:invalid {
border-color: red;
}
</style>
By implementing these changes, your contact form will now enforce proper email formatting, improving data quality and user experience.
Not yet included in a published release.