0

I have an input with email pattern validator. (regex ^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$)

If I type a long invalid email the form will crash. Surprisingly it will work fine for long valid input.

Has anyone experienced this before? Please share your workaround if you have.

Thanks in advance.

kshetline
  • 12,547
  • 4
  • 37
  • 73
Ngoc Nam Nguyen
  • 493
  • 6
  • 15
  • Can you show how the regex is being used? Also, just how long is "long"? No crash for relatively short invalid email addresses? – kshetline May 04 '18 at 01:31
  • I would suggest to experiment with the pattern shown here: https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript?page=1&tab=votes#tab-top – wp78de May 04 '18 at 06:00
  • @kshetline Yes, short email like 10 or 15 characters works fine. I tested with "thisismyveryveryveryverylongemail" and it starts lagging since "long" and officially crash when i reach "email". – Ngoc Nam Nguyen May 06 '18 at 23:56
  • @wp78de thanks, that pattern also fail for 30+ characters – Ngoc Nam Nguyen May 07 '18 at 00:09
  • All of them? There are many varieties in the answers of the linked question. – wp78de May 07 '18 at 00:12
  • Sorry, my bad. It was actually because of another dependent input also have wrong regex that crash the system. Correct regex can be found here http://emailregex.com/ or the accepted answer – Ngoc Nam Nguyen May 08 '18 at 01:55

1 Answers1

0

Try this: ^\w+(?:[\.-]\w+)*@\w+(?:[\.-]\w+)*(?:\.\w{2,3})+$

The crashing has to with the efficiency of your regex. In particular, those ? after the [\.-] are unnecessary and causing many more repetitions than necessary. Some regex works well with matching solutions, but catastrophically backtrack when presented with a string that doesn't match.


Edit: These other two solutions won't work for Angular because it is Javascript regex, but they're still useful for general reference.

Best, using possessive quantifiers: ^\w++(?:[\.-]\w++)*@\w++(?:[\.-]\w++)*(?:\.\w{2,3})+$

2nd best, with atomic groups: ^(?>\w+)(?:[\.-](?>\w+))*@(?>\w+)(?:[\.-](?>\w+))*(?:\.\w{2,3})+$

Graham
  • 3,153
  • 3
  • 16
  • 31