Email validation in HTML With Source Code

Email validation is one of the most important things when we want to collect email addresses from our users. The most common use of "email validation on javascript" is in the contact us page of any website. In this post, we will learn how email validation in HTML works.

Email validation in HTML

Email Validation in HTML Type Attribute

Using the HTML type attribute we can easily validate an email. But this technique works only when we submit our HTML form by clicking the submit button. That means if you submit your form using javascript this technique will not work.
Another issue is this technique doesn’t check the domain part properly. You may already know an email has three-part local, symbol and domain. For more details please, learn what is the valid format of an email address.

 <form action="#">
    <label for="Email">Email*</label><br><br>
    <input id="Email" type="email" type="email" placeholder="Email Address"><br>
    <input  type="submit">
</form>

So the valid way of validating an email in HTML is to use the pattern attribute.

Email Validation in HTML Pattern attribute

HTML pattern attribute is one of the cool things to validate input data. We can validate text, date, search, URL, tel, email, and password. Now we will learn how to “validate email using HTML pattern attribute”.
HTML Pattern attribute takes a regular expression and matches the input value with the regular expression.
Note: you need to use single quotes in the pattern attribute, and don’t use forward slash in the very first and last place.

Regular expression for email validation

/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
<form action="#">
    <fieldset>
        <legend>Email Validation in HTML</legend>
        <label for="Email">Email* <br>
        <input pattern='^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' required type="text" id="Email"><br> <br>
        <input type="submit">
    </fieldset>
</form>
Note: if you want to show a custom error message you can use email validation on javascript.
Still you face problems, feel free to contact with me, I will try my best to help you.