137

It is said "With HTML5, we need no more js or a server side code to check if the user's input is a valid email or url address"

How can I validate email after a user enter? and without JS how to display a message if the user enter a wrong form of his/her email address.

<input type="email" pattern="[^ @]*@[^ @]*" placeholder="Enter your email">
<input type="submit" value="Submit">
4
  • 67
    You always need to validate on the server side. A clever client can bypass any client-side security measure. Commented Oct 26, 2013 at 10:50
  • This answer might help when trying to set up HTML5 form validation. Of course you would probably still need server-side validation though.
    – Joeytje50
    Commented Nov 18, 2014 at 18:04
  • 2
    regex Email validation should never be used under any circumstances. Regex checks have too many flaws. The best way to "validate" an email addresses is to simply have them type it twice and run a Regex check that gives a WARNING to the user that it doesn't look like a valid email address if it does not match the pattern, and asks the user to double check. This way, if it actually is valid, but regex is failing (like it so often does) the user can just acknowledge that they know it is valid and continue. Far too many sites use regex validation and it is frustrating for many users.
    – Soundfx4
    Commented Mar 15, 2016 at 16:10
  • 3
    Asking the user to input the same email address twice is useless. If you do not know their email address, asking to type it twice does not improve the odds. If they do know their email address, asking to type it twice is just poor UI. Commented Jun 29, 2020 at 7:23

13 Answers 13

147

In HTML5 you can do like this:

<form>
<input type="email" placeholder="Enter your email">
<input type="submit" value="Submit">
</form>

And when the user press submit, it automatically shows an error message like:

Error Message

12
  • 3
    What is the benefit of the pattern here? Specifying the type as email already includes a built in pattern to determine this. Commented Oct 26, 2013 at 10:58
  • 4
    @RichBradshaw: Yes, you are correct. No need to specify the pattern (I just copied code from OP, I corrected now :) )
    – Midhun MP
    Commented Oct 26, 2013 at 11:01
  • 7
    @MichaelDeMutis: You can use the required attribute
    – Midhun MP
    Commented Mar 22, 2014 at 8:08
  • 50
    the email doesn't check for .com in an email. It only checks @ sign. Ex. I can enter example@gmail and save the form. though it is not a valid email address. Is there workaround to check properly [email protected]?
    – Liz.
    Commented Jan 24, 2017 at 7:16
  • 15
    @Liz. example@gmail might not be a valid email but it is a valid email address format.
    – pajaja
    Commented Jul 11, 2017 at 12:28
65

The input type=email page of the www.w3.org site notes that an email address is any string which matches the following regular expression:

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

Use the required attribute and a pattern attribute to require the value to match the regex pattern.

<input
    type="text"
    pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
    required
>
12
  • 17
    You must insert the pattern without the two '/' and the start '^' and end '$' symbol. Like these [a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*
    – Victor
    Commented Nov 7, 2014 at 11:22
  • 5
    @Victor Sorry, but you're partially wrong. This symbols are important without them the pattern will start to match everywhere in the string and make it useless. Where you're correct is letting the slashes out.
    – Hexodus
    Commented Feb 13, 2016 at 11:37
  • @Victor your answer worked for me. OP's regex gave me a false positive saying to match the form's requirements even when it's a valid email address. Perhaps it's that I'm not using regular HTML, but using React JS to render the HTML form.
    – Ka Mok
    Commented Oct 17, 2016 at 7:20
  • 1
    @vikramvi It seems that the OP edited the answer so I can't be sure any more. For my purposes this regex is to complex. I usualy do something like /..+@.+\...+/
    – Hexodus
    Commented May 3, 2021 at 10:56
  • 1
    @vikramvi It marks the start and end of the regular expression. Otherwise it's used to escape the next character or sign. See: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
    – Hexodus
    Commented May 3, 2021 at 12:05
20

Using [a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,} for [email protected] / [email protected]

5
  • Still rejects one-letter domain names.
    – user149341
    Commented Nov 23, 2016 at 16:17
  • 1
    This allows 1 letter/number domains: [a-zA-Z0-9.-_]{1,}@[a-zA-Z0-9.-]{1,}[.]{1}[a-zA-Z0-9]{2,}
    – Rudder
    Commented May 28, 2017 at 17:37
  • 1
    Also note that, for example, postmaster@ai is a valid email address and this regexp would ban that, too. (Source: serverfault.com/q/154991/104798) Commented May 29, 2018 at 5:57
  • Thanks @VanNguyen your example it's really helphelpful.
    – user10753297
    Commented Dec 31, 2018 at 12:07
  • postmaster@ai is not a valid public e-mail address. It's a valid private e-mail address.
    – PRMan
    Commented Nov 11, 2021 at 16:40
18
document.getElementById("email").validity.valid

seems to be true when field is either empty or valid. This also has some other interesting flags:

enter image description here

Tested in Chrome.

1
  • 1
    If you include the required attribute in the form element, it won't allow the form to be submitted with the form element empty.
    – mti2935
    Commented Oct 2, 2020 at 14:38
14

A bit late for the party, but this regular expression helped me to validate email type input in the client side. Though, we should always do verification in server side also.

<input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">

You can find more regex of all kinds here.

12

TL;DR: The only 100% correct method is to simply check for @-sign somewhere in the entered email address and then send a validation message to given email address. If the end user can follow validation instructions in that email message, the entered email address is correct.

Long answer:

David Gilbertson wrote about this years ago:

There are two questions we need to ask:

  1. Did the user understand that they were supposed to type an email address into this field?
  2. Did the user correctly type their own email address into this field?

If you have a well laid-out form with a label that says “email”, and the user enters an ‘@’ symbol somewhere, then it’s safe to say they understood that they were supposed to be entering an email address. Easy.

Next, we want to do some validation to ascertain if they correctly entered their email address.

Not possible.

[...]

Any mistype will definitely result in an incorrect email address, but only maybe result in an invalid email address.

[...]

There is no point in trying to work out if an email address is ‘valid’. A user is far more likely to enter a wrong and valid email address than they are to enter an invalid one.

In other words, it's important to notice that any kind of string based validation can only check if the syntax is invalid. It cannot check if the user can actually see the email (e.g. because the user already lost credentials, typed address of somebody else or accidentally typed work email address instead of their personal email address for the given use case). How often the question you're really after is "is this email syntactically valid" instead of "can I communicate with the user using given email address"? If you validate the string more than "does it contain @", you're trying to answer the former question. Personally, I'm always interested about the latter question only, namely can the recipient actually read the message?

For example, if I accidentally type [email protected] as my email address, do you think you can truly validate that string without trying to send me an email message? That's obviously syntactically valid email address but I cannot read any message sent to that address. Was that the type of email address you were actually trying to collect?

In addition, some email addresses that may be syntactically or politically invalid, do work. For example, postmaster@ai does work in practice even though TLDs should not have MX records so this is syntactically invalid address. Also see discussion about email validation on the WHATWG mailing list (where HTML5 is designed in the first place).

9

I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            this.setCustomValidity('');
        }
    });
})
1
  • Please don't only post link answers. Just put the essential parts of the link in your answer
    – Rizier123
    Commented Feb 17, 2015 at 1:51
9

Here is the example I use for all of my form email inputs. This example is ASP.NET, but applies to any:

<asp:TextBox runat="server" class="form-control" placeholder="Contact's email" 
    name="contact_email" ID="contact_email" title="Contact's email (format: [email protected])" 
    type="email" TextMode="Email" validate="required:true"
    pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*" >
</asp:TextBox>

HTML5 still validates using the pattern when not required. Haven't found one yet that was a false positive.

This renders as the following HTML:

<input class="form-control" placeholder="Contact's email" 
    name="contact_email" id="contact_email" type="email" 
    title="Contact's email (format: [email protected])" 
    pattern="[a-zA-Z0-9!#$%&amp;'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">
3

You can follow this pattern also

<form action="/action_page.php">
  E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
  <input type="submit">
</form>

Ref : In W3Schools

1
  • 1
    <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="please enter valid email [[email protected]]."> you can add title also to show a validity message.
    – imdzeeshan
    Commented Apr 30, 2019 at 11:40
2

Using HTML 5,Just make the input email like :

<input type="email"/>

When the user hovers over the input box, they will a tooltip instructing them to enter a valid email. However, Bootstrap forms have a much better Tooltip message to tell the user to enter an email address and it pops up the moment the value entered does not match a valid email.

3
  • 2
    But, this does not invalidate cases like "abc@gmail". Commented Sep 19, 2019 at 7:24
  • yes I think so , I would like valide if the user put gmail or hotmail for example if my user put other then dont let them continue with my login, do you know how can i do that?
    – simon
    Commented Jan 31, 2020 at 19:39
  • It also doesn't take into account European, Japanese, Chinese chars, which are allowed since 2012. Every browser I tried it doesn't allow them. Even W3c, goes against their own advice here, and browser vendors just copy too restrictive input syntax. Commented Sep 18, 2023 at 2:47
2

According to MDN, this RegExp is ok to validate emails, as emails that meet specifications should match it.

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}
  [a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
2
  • Your MDN link has become obsolete. :( Commented Nov 26, 2022 at 0:08
  • 1
    Went ahead and replaced the link with a new one. Don't know if you still need it, but it should work now.
    – ZachT112
    Commented Dec 21, 2022 at 3:36
0

It is very difficult to validate Email correctly simply using HTML5 attribute "pattern". If you do not use a "pattern" someone@ will be processed. which is NOT valid email.

Using pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" will require the format to be [email protected] however if the sender has a format like [email protected] (or similar) will not be validated to fix this you could put pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" this will validate ".com.au or .net.au or alike.

However using this, it will not permit [email protected] to validate. So as far as simply using HTML5 to validate email addresses is still not totally with us. To Complete this you would use something like this:

<form>
<input id="email" type="text" name="email" pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" required placeholder="Enter you Email">
<br>
<input type="submit" value="Submit The Form">
</form>

or:

<form>
<input id="email" type="text" name="email" pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" required placeholder="Enter you Email">
<br>
<input type="submit" value="Submit The Form">
</form>

However, I do not know how to validate both or all versions of email addresses using HTML5 pattern attribute.

2
  • 1
    regex checks should never be used under any circumstances. There are too many patterns and they have too many flaws. For example, [email protected] is considered invalid to many regex checks when, in fact, it is 100% valid. Regex is a thorn in mine and many other users sides and it has to go. An alternative method to ensure a user is entering a valid email address needs to be used.
    – Soundfx4
    Commented Mar 15, 2016 at 16:12
  • 1
    Also note that, for example, postmaster@ai is a valid email address and this regexp would ban that, too. (Source: serverfault.com/q/154991/104798) Commented May 29, 2018 at 5:56
-3

If you just learning HTML and you want a simple solution this code will do the job for you

 <form>
    <input type="email" placeholder="Enter your email">
    <input type="submit" value="Submit" required>
  </form>

But if you are a professional and want something secure and keep your database clean there is a paid service called DeBounce API it validates the email on the frontend that way you don't get an invalid email in your data it works like this,

if an invalid email is provided, the email address will be converted to a placeholder (which is equal to an empty input), so if the email field is a mandatory one, the form cannot submit here is there website https://debounce.io/

Not the answer you're looking for? Browse other questions tagged or ask your own question.