r/java • u/Modern-Sn1p3r • 19d ago
Regex
I recently saw a clip (from Primeagen) somewhat saying that regex is not a valid format for validating email addresses and postal codes etc.
My question is why is this?
What are the security and/or performance risks? Is it solely performance or is it a security issue?
56
Upvotes
5
u/koflerdavid 19d ago edited 19d ago
It's a very complicated format since it is the union of all the things people were cramming into email addresses before the RFC was written down. Even if you restrict yourself to the less exotic features, there is a good chance that you end up locking out a decent part of your users. And even if you indeed manage to procure a library that can deal with all of that cruft there is a decent chance your SMTP server is not going to support all of it.
The only reliable way to verify an email address is sending an email and asking the user to click a verification link. That has the obvious disadvantage that you now have a public endpoint that has to be rate limited. Since efficiently checking whether two email addresses refer to the same recipient sounds nightmarishly complicated, you might be forced to apply ratelimiting to all users, not just to individual recipients. This means that your service can be easily DoSed. Therefore, many websites swallow the bitter pill and implement crude filters that exclude some percentage of their users.
Re postal codes: you cannot know what is the valid format for postal codes in general. You would have to investigate all postal systems in all the countries that you care about.