Html code validate email address
HTML does not have a built-in way to validate email addresses. However, you can use JavaScript or a regular expression to validate an email address. Here are a few examples:
Using JavaScript:
<form>
<input type="email" id="email" name="email">
<button type="submit">Submit</button>
</form>
<script>
const emailInput = document.getElementById('email');
emailInput.addEventListener('input', function() {
const email = emailInput.value;
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailRegex.test(email)) {
alert('Invalid email address');
}
});
</script>
Using a regular expression:
<form>
<input type="email" id="email" name="email">
<button type="submit">Submit</button>
</form>
<script>
const emailInput = document.getElementById('email');
emailInput.addEventListener('input', function() {
const email = emailInput.value;
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailRegex.test(email)) {
alert('Invalid email address');
}
});
</script>
Using HTML5 pattern attribute:
<form>
<input type="email" id="email" name="email" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}">
<button type="submit">Submit</button>
</form>
Note that the HTML5 pattern attribute is not supported in older browsers, and the regular expression used in the examples above is not foolproof. It's always a good idea to use a more robust email validation library or service if you need to validate email addresses in a production environment.
Here's a breakdown of the regular expression used in the examples above:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-), underscore (_), percent (%), plus sign (+)@
matches the @ symbol[a-zA-Z0-9.-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-)\.
matches a period (.) character[a-zA-Z]{2,}
matches the domain extension (it must be at least 2 characters long)$
matches the end of the string
This regular expression matches most common email address formats, but it's not perfect and may not match all valid email addresses.