-1

I have a regex for e-mail validation which is constructed as following:

const emailRegexp = /[a-z0-9._%+]+@[a-z0-9]+(\.[a-z]{2,10}){1,2}$/;

Examples:

aaa@aaa-aaa.com - for this e-mail, validation works and it blocks the users from submiting the form aa-aa@aaa.com - for this e-mail, validation doesn't work.

How to disallow all hyphens in this particular "emailRegexp" variable?

Piotr Sobuś
  • 302
  • 4
  • 8
  • 2
    Prepend the pattern with `^` – Wiktor Stribiżew Jun 13 '19 at 11:14
  • 1
    But...why do you want to [disallow valid emails](https://www.reddit.com/r/softwaregore/comments/7pwbdj/my_email_address_has_a_hyphen_in_it/)? `coca-cola.com` is a real domain that exists. – VLAZ Jun 13 '19 at 11:24
  • 2
    It's probably worth noting.... **A valid email address *can* contain a hyphen**. *Any* attempt to validate email addresses with regex is flawed (including the ridiculous 1000+ character"RFC compliant" regexes you'll find online); my advice has always been to use the loosest regex possible (e.g. `^[^@]+@[^@]+$`) and then - if you really need to - ensure that the address is truly valid by sending them a **validation email** (with a confirmation link) – Tom Lord Jun 13 '19 at 12:42
  • @TomLord indeed. The problem is that even if you somehow figure out that the email is *valid* as per the specs, that doesn't mean *it exists*. A user signing up with a non-existent email is a way worse problem than them signing up with an email that contains a hyphen, or an apostrophe, or a plus sign, or everything else a lot of developers deem "unworthy" to be in an email. If you want their email, it's to *contact them*, so the only validation that matters is "can you contact the user via this email". – VLAZ Jun 13 '19 at 13:01

1 Answers1

0

Put a '^' at the start of the pattern, this asserts the position at the start of the string.

^[a-z0-9._%+]+@[a-z0-9]+(\.[a-z]{2,10}){1,2}$

Tim VN
  • 1,183
  • 1
  • 7
  • 19