133

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">
Alireza Sabahi
  • 647
  • 1
  • 12
  • 35
abcid d
  • 2,821
  • 7
  • 31
  • 46
  • 62
    You always need to validate on the server side. A clever client can bypass any client-side security measure. – Benjamin Gruenbaum Oct 26 '13 at 10:50
  • [This answer](http://stackoverflow.com/a/27000682/1256925) might help when trying to set up HTML5 form validation. Of course you would probably still need server-side validation though. – Joeytje50 Nov 18 '14 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 Mar 15 '16 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. – Mikko Rantalainen Jun 29 '20 at 07:23

13 Answers13

143

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

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • 3
    What is the benefit of the pattern here? Specifying the type as email already includes a built in pattern to determine this. – Rich Bradshaw Oct 26 '13 at 10:58
  • 3
    @RichBradshaw: Yes, you are correct. No need to specify the pattern (I just copied code from OP, I corrected now :) ) – Midhun MP Oct 26 '13 at 11:01
  • Thank you very much, Rich! I forgot to put the code inside `
    `
    – abcid d Oct 26 '13 at 11:03
  • This is all fine and yay but how do you make it required as well? – Michael Fever Mar 21 '14 at 19:57
  • 7
    @MichaelDeMutis: You can use the `required` attribute – Midhun MP Mar 22 '14 at 08:08
  • Tried this, very buggy. How do you reset it once its fixed? Good luck.. easier to do your own checking in jquery – Michael Fever Mar 24 '14 at 05:28
  • I have tried it. Once i enter the wrong email. it shows error but if i corrected it , the error is still there. – sambit.albus May 14 '14 at 02:42
  • If you want to run the validation without clicking on the submit button (for instance, if you will submit the data via ajax), then you can call `.checkValidity()` on the field to trigger the validation. More info on http://stackoverflow.com/questions/11866910/how-to-force-a-html5-form-validation-without-submitting-it-via-javascript-jquery – Marcelo Diniz May 15 '14 at 12:40
  • @RichBradshaw I have read that different browsers implement the email pattern differently, [see this blog](http://www.html5-tutorials.org/form-validation/validating-email/). Thus, adding a pattern to the email element could help to match up client and server side validation more accurately. However, the blog I linked, does not recommended to add a pattern to an email type. – Ben Aug 16 '15 at 10:21
  • 45
    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 `example@gmail.com`? – Liz. Jan 24 '17 at 07:16
  • 13
    @Liz. `example@gmail` might not be a valid email but it is a valid email address format. – pajaja Jul 11 '17 at 12:28
  • 1
    @Liz: in the reality, the browser can only check for `@` because, for example, `postmaster@ai` is *a prefectly working email address* even though *it's syntactically invalid*. In addition, because you can technically use UTF-8 on both sides of the @-sign, there's no point trying to use more complex matching. (Yeah, if you really want, you could do `[^@]@[^@]` but that's about the most complex match you can do in real world.) For more information, see https://stackoverflow.com/a/50577660/334451 – Mikko Rantalainen Jun 29 '20 at 07:20
61

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
>
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Stefan Ciprian Hotoleanu
  • 2,202
  • 1
  • 23
  • 30
  • 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 Nov 07 '14 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 Feb 13 '16 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 Oct 17 '16 at 07:20
  • I almost down voted this because the correct answer is to use `type="email"` and check the `valid` boolean property on the DOMNode - no need to repeat the underlying regex – Dominic Jan 27 '17 at 14:25
  • Thank you for mentioning this. – Stefan Ciprian Hotoleanu Jan 27 '17 at 14:29
  • Something like `...@a.aa` is still an accepted value? – eozzy May 19 '17 at 01:49
  • If HTML 5 using above regex, does it mean internationalised email addresses will fail to pass the validation? – shiouming Jun 18 '18 at 10:08
  • @Hexodus OP doesn't match valid email address one.two@gmail.com, can you clarify why ? Also why did you suggest to remove '/' , isn't it part of regex ? – vikramvi May 03 '21 at 07:06
  • 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 May 03 '21 at 10:56
  • @Hexodus am learning RegEx and didn't find any reference to "/", what is it suppose to do at start and end of regex ? – vikramvi May 03 '21 at 11:09
  • 1
    @vikramvi It marks the start and end of the regular expression. Otherwise it's used to escape the next character or sign. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet – Hexodus May 03 '21 at 12:05
  • Thanks, but I didn't get your answer "...you're correct is letting the slashes out. ", why is that ? As per mozilla documentation slashes are part of reg ex literal. – vikramvi May 04 '21 at 05:44
20

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

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Van Nguyen
  • 319
  • 2
  • 4
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.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
  • 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 Oct 02 '20 at 14:38
11

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.

NBSamar
  • 904
  • 12
  • 20
10

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 mikok.rantalainen@gmail.com 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).

Mikko Rantalainen
  • 14,132
  • 10
  • 74
  • 112
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('');
        }
    });
})
karic83
  • 91
  • 1
  • 3
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: xxx@xxx.xxx)" 
    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: xxx@xxx.xxx)" 
    pattern="[a-zA-Z0-9!#$%&amp;'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">
Keith H.
  • 338
  • 3
  • 5
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

skpaik
  • 360
  • 5
  • 12
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.

Fabian Madurai
  • 317
  • 3
  • 4
  • But, this does not invalidate cases like "abc@gmail". – NBSamar Sep 19 '19 at 07: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 Jan 31 '20 at 19:39
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])?)*$/
ZachT112
  • 31
  • 5
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 someone@email.com however if the sender has a format like someone@email.net.au (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 someone@email.com 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.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Keith
  • 91
  • 1
  • 1
  • 5
  • 1
    regex checks should never be used under any circumstances. There are too many patterns and they have too many flaws. For example, someone+customwordhere@email.com 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 Mar 15 '16 at 16:12
  • 1
    Also note that, for example, `postmaster@ai` is a valid email address and this regexp would ban that, too. (Source: https://serverfault.com/q/154991/104798) – Mikko Rantalainen May 29 '18 at 05: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/

Dharman
  • 30,962
  • 25
  • 85
  • 135
Kasem777
  • 737
  • 7
  • 10