HTML Email pattern
Property: Email Input Pattern
The pattern
attribute in HTML is used to specify a regular expression that the value of an <input>
element must match to be considered valid. When applied to an <input type="email">
element, the pattern
attribute allows you to define a custom format for email addresses, enabling more specific validation beyond the browser’s default email format checking. This is particularly useful for enforcing specific domain requirements or custom email formats within your application.
Purpose of the pattern
Property
The primary purpose of the pattern
attribute is to:
- Enforce Custom Email Formats: Define precisely what constitutes a valid email address for your application.
- Improve Data Accuracy: Ensure that users enter email addresses that conform to specific rules or formats required by your system.
- Enhance User Experience: Provide immediate feedback to users if their input does not match the required pattern.
- Client-Side Validation: Validate email input on the client side before submitting the form, reducing server load and improving response times.
Syntax of the pattern
Attribute
The pattern
attribute is added to the <input type="email">
element in the following way:
<input type="email" id="emailPattern" name="email" pattern="your_regular_expression" />
Here, your_regular_expression
is a string representing the regular expression that the email input must match.
Key Points about the pattern
Attribute
- The value of the
pattern
attribute is a regular expression. - The regular expression should be designed to match the desired email format.
- The
pattern
attribute works in conjunction with other validation attributes likerequired
. - Browsers display an error message if the input value does not match the specified pattern.
Examples of Using the pattern
Attribute
Let’s explore various examples showcasing the use of the pattern
attribute with email input fields. Each example includes HTML and, where necessary, JavaScript code snippets to illustrate the implementation and behavior.
Basic Example: Validating a Simple Email Format
This example demonstrates a simple email format validation using the pattern
attribute.
<form>
<label for="emailSimple">Email:</label>
<input
type="email"
id="emailSimple"
name="emailSimple"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}"
required
/>
<button type="submit">Submit</button>
</form>
In this case, the regular expression [a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}
checks for a basic email format:
- One or more alphanumeric characters, dots, underscores, percentages, plus or minus signs before the @ symbol.
- One or more alphanumeric characters or dots after the @ symbol.
- A dot followed by two or more alphabetic characters for the domain extension.
Example: Validating Email with a Specific Domain
This example shows how to validate email addresses to ensure they belong to a specific domain.
<form>
<label for="emailDomain">Email (@example.com only):</label>
<input
type="email"
id="emailDomain"
name="emailDomain"
pattern="[a-z0-9._%+-]+@example\\.com"
required
/>
<button type="submit">Submit</button>
</form>
Here, the regular expression [a-z0-9._%+-]+@example\\.com
ensures that the email address ends with “@example.com”. The \.
is used to escape the dot, as .
has a special meaning in regular expressions (any character).
Example: Validating Email with a Custom Error Message
To provide a more user-friendly experience, you can use JavaScript to set a custom error message when the email input does not match the pattern.
<form>
<label for="emailCustomError">Email:</label>
<input
type="email"
id="emailCustomError"
name="emailCustomError"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}"
required
/>
<button type="submit">Submit</button>
</form>
<script>
const emailCustomErrorInput = document.getElementById("emailCustomError");
emailCustomErrorInput.addEventListener("invalid", function (event) {
if (emailCustomErrorInput.validity.patternMismatch) {
emailCustomErrorInput.setCustomValidity(
"Please enter a valid email address."
);
} else {
emailCustomErrorInput.setCustomValidity("");
}
});
emailCustomErrorInput.addEventListener("input", function (event) {
emailCustomErrorInput.setCustomValidity(""); // Clear custom error on input
});
</script>
In this example, an event listener is added to the email input field. When the input is invalid due to a pattern mismatch, a custom error message is set using setCustomValidity()
. The error message is cleared when the user starts typing in the input field.
Example: Complex Email Validation
This example demonstrates a more complex email validation that checks for a specific format and length constraints.
<form>
<label for="emailComplex">Email (must be 8-20 characters long):</label>
<input
type="email"
id="emailComplex"
name="emailComplex"
pattern="[a-z0-9._%+-]{8,20}@[a-z0-9.-]+\\.[a-z]{2,}"
required
/>
<button type="submit">Submit</button>
</form>
Here, the regular expression [a-z0-9._%+-]{8,20}@[a-z0-9.-]+\\.[a-z]{2,}
ensures that the part of the email address before the “@” symbol is between 8 and 20 characters long.
Example: Live Validation with JavaScript
This example shows how to use JavaScript to provide live validation feedback as the user types.
<form>
<label for="emailLiveValidation">Email:</label>
<input
type="email"
id="emailLiveValidation"
name="emailLiveValidation"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}"
required
/>
<span id="emailValidationResult"></span>
<button type="submit">Submit</button>
</form>
<script>
const emailLiveValidationInput = document.getElementById(
"emailLiveValidation"
);
const emailValidationResultSpan = document.getElementById(
"emailValidationResult"
);
emailLiveValidationInput.addEventListener("input", function (event) {
if (emailLiveValidationInput.checkValidity()) {
emailValidationResultSpan.textContent = "Valid email!";
emailValidationResultSpan.style.color = "green";
} else {
emailValidationResultSpan.textContent = "Invalid email!";
emailValidationResultSpan.style.color = "red";
}
});
</script>
In this example, an event listener is added to the email input field to check the validity of the input as the user types. The checkValidity()
method is used to determine if the input matches the specified pattern. The result is displayed in a span element next to the input field.
Browser Support
The pattern
attribute is supported by all modern browsers. Hereβs a general compatibility overview:
- Chrome: Yes
- Edge: Yes
- Firefox: Yes
- Safari: Yes
- Opera: Yes
- Internet Explorer: Version 10 and above
Tips and Best Practices
- Provide Clear Instructions: Inform users about the expected email format using clear labels and instructions.
- Use Simple Patterns: Keep regular expressions as simple as possible for better performance and readability.
- Test Thoroughly: Test your patterns with various email formats to ensure they work as expected.
- Consider Server-Side Validation: Always validate email addresses on the server side to prevent malicious input and ensure data integrity.
- Use Custom Error Messages: Provide custom error messages to guide users in correcting invalid input.
Conclusion
The pattern
attribute is a powerful tool for validating email input fields in HTML forms. By defining custom regular expressions, you can enforce specific email formats, improve data accuracy, and enhance the user experience. Combining the pattern
attribute with JavaScript for custom error messages and live validation can further improve the usability and effectiveness of your forms.