Validating email is one of the things you'll "encounter" often when building an app (web/mobile). If you're new to programming, you'll probably wonder on how to do that. Using Regex is one of the easiest way to do the validation.
There are a few constraints to make sure a text is a valid email address:
- @ is present
- Top level domain can't start with dot ".".]
- There should be characters before @.
- Email/Personal info can't start with a dot "."
- Email/Personal info can't end with a dot "."
- No double dots.
- Characters, digits, underscore, and dash are allowed.
Here are the regex to use to check those constraints:
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
Here how you can put it in your JavaScript code:
const isValidEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailAddress);
if (isValidEmail){
return true;
} else {
return false;
}
Check this link for more detailed information about this:
https://www.w3resource.com/javascript/form/email-validation.php
Top comments (5)
If it's front-end you're working on, having an input field be of
type=email
will do you well enough, and email addresses are notoriously complicated. As a trivial example, "moopet@example.com" will pass that validation, but "moopet+dev@example.com" won't. The same with "moopet@127.0.0.1" (works) and "moopet@127.0.0.0.0.0.123456" (apparently this is also valid...) "moopet@localhost" is a valid email address but won't pass your regex. I'm sure there are plenty more exceptions.I'm not saying it's wrong to do these sorts of tests, but you're going to annoy someone at some point who's trying and failing to sign up to your site and has an address that works find everywhere else.
EDIT: it's amusing that DEV automatically makes most of those into email links (except "moopet@localhost") so I guess they're using something that checks
@
and.
and that's all.yup, the interpreters usually don't mind about email addresses without domain, because @localhost is only reachable in your own context so... why bother?
You're right about the rest.
Currently with the RFC5322 you can get a 99.99% valid regex if you need it but it's a bit... well... judge by yourself:
Source
I won't actually recommend using it unless it's completely necessary.
Hey, thanks for letting me know about this! I actually used
type=email
in my input field too, but the reason for using this regex was to help me detect invalid email address according to it and show some alert on the frontend.Do you know if input field send some sort of event or something that I could catch to fully replace regex with
type=email
in the input field?No, sorry, I don't know much about it really beyond that! I'm pretty sure there's the
pattern
attribute you can use, but the html5pattern page on email regex recommends against using it that way.Hi @james
Check this:
Form input validation WITHOUT JavaScript
JoelBonetR ・ Aug 15 ・ 2 min read
Best regards