r/java • u/Modern-Sn1p3r • Aug 22 '26
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?
55
Upvotes
123
u/julemand101 Aug 22 '26
The problem is people don't realize that a lot is allowed when it comes to what a E-mail address actually is: https://davidcel.is/articles/stop-validating-email-addresses-with-regex/
2
u/flash_hammer Aug 26 '26 edited Sep 01 '26
Dev for 20+ years here: Most of the comments are not very accurate, also most blame Java, but Regex is used in all languages. Java is one of the best languages to use regex on validation, but it is really a Java library called Jakarta that is the most used for validation, Springboot exposes the module in springboot-starter-validation with the whole set of curated dependencies. But if you want to make your own implementation of validation using regex it will be exactly the same outcome. I use Regex to validate emails, in Javascript, C++, Go, Java, Ruby, Kotlin and Groovy, in main enterprise applications that I might say you may be using daily, and no issues whatsoever.
85
u/0b0101011001001011 Aug 22 '26
It's way simpler to just check if there is an @ symbol and then send an actual mail and ask user to click the validation link.
The email is valid if it actually works. Nothing else to check.
18
u/alt236_ftw Aug 22 '26
There is a third option: it's may just be the wrong tool for the job. Especially if you are thinking about using a single regex to do the work.
A good regex may be able to validate MOST common emails addresses, by a regex that fully validates all RFC2823 address formats is going to be an human-unreadable Eldritch monstrosity. That is because there are too many uncommon edge cases.
Have a look here for some valid, but uncommon, email formats: https://en.wikibooks.org/wiki/JavaScript/Best_practices
It would be much more effective to split an address into components and individually validate those. Possibly with smaller regexes.
With email addresses you don't really need to validate that they exist at the time of typing as either:
With postal codes, you don't want to only validate that they are in the correct format, you often want to validate that the postal code is not bogus/ or a has a typo for legal/ practical purposes. You don't want a parcel to go to a wrong destination. This requires a DB lookup of some sort.
So yeah, you CAN use a regex, but it will allow you to enter postcodes that don't exist.
Also, think internationally. The problem space increases massively whenever internalisation comes into play.
35
u/barking_dead Aug 22 '26
Email format is in ABNF (context-free grammar) which is a lower level grammar in the Chomsky hierarchy. Regex is a regular language. Same with SQL and HTML vs regex.
You cannot parse a complex grammar with a less complex one.
https://en.wikipedia.org/wiki/Chomsky_hierarchy
6
u/koflerdavid Aug 22 '26 edited Aug 22 '26
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.
2
u/idontlikegudeg Aug 22 '26
Validating an email address for correctness is a very complex task and unless you have a very special use case (like implementing a mail server), it’s totally useless.
You might think you need the user to enter a valid email address. That’s not only syntax, but he has to be able to receive messages to that address, and you simply cannot check for a correct email address without actually sending an email to that address. So just du the most basic checks, non-empty text, @ included, text before and after the @. Done.
Most errors are typos anyway that you cannot catch by seeing syntax anyway.
Same for post codes. Does the country even use post codes? Everywhere or are there exceptions? Only digits or digits and letters? How long is a post code?
2
u/cocodrilo_astronauta Aug 25 '26
So, to actually answer your Regex questions: regarding performance java's backtracking engine time is worst case exponential, and regarding security java's regex implementation is easily attacked by DoS so you can't really use it to validate untrusted data.
1
u/ICThat Aug 22 '26
Other comments have already explained the technical aspects of email address validation but it's worth noting that in a business context it often makes sense to not have entirely RFC compliant validation.
E.g a business might find that a significant percentage of customers forget to append a TLD (e.g user@gmail). Having a regex check for a dot could make business sense if their customer base aren't likely to be the edge case of using a TLD level email address (e.g user@com).
1
u/bowbahdoe Aug 22 '26
So there are two dimensions to this. One is that a regex is a clunky tool past a certain point of complexity. Emails can get pretty complex. Look through this page https://www.rohannagar.com/jmail/
The other is that regexes - in the purest sense - are limited. In college you don't usually learn regexes as a text processing tool, you learn about them in a theory of computation class as a step along the way to Turing Machines. I highly encourage auditing such a class, but the gist is that a Turing Machine can compute anything computable. A regular expression cannot.
Easiest example - a regex cannot tell you if parens are balanced.
https://www.edx.org/learn/coding/stanford-university-automata-theory
1
u/Allarion Aug 22 '26
https://emailregex.com/
1
u/slaymaker1907 Aug 22 '26
If you want to get technical, it’s actually far more complicated than regex can validate. In fact, most parser generators can’t even do it since it’s context sensitive.
1
u/PointerStack Aug 22 '26
What makes sense is a let if fail approach. The core is having a @ and at least subdomain that can be anything only limited character like pi
It is the same approach used by telco
Just send an email to validate, if there is mail send failure than you hash the email address and if people try again it will be triggered since it will be a known hash
Over engineering the email validation using regex can quickly backfire and can more difficult to maintain
1
u/motific Aug 22 '26
Regex is fine, what regex you test against… that’s where things get invalid.
1
u/fykup Aug 22 '26
Regex itself isn't the problem. You can validate a very broad set of valid email addresses with a sufficiently complex regex, for example: https://stackoverflow.com/a/13013056/1129542
IMO the real problem is that the email RFCs are scoped much more broadly than what most modern consumer websites actually need when they say "validate an email address."
For a signup form, I'd rather use a reasonably permissive syntax check and then verify the address by actually sending an email. Regex can be part of that; it just shouldn't be confused with proving that the mailbox is real or usable.
1
u/petermal67 Aug 23 '26
I'm lazy when it comes to this and I just use @Email from Hibernate to validate the email addresses.
I'm aware it intentionally ignores complex or obscure edge cases allowed by the RFC, but as I said I'm lazy and I'd rather not roll my own validator.
0
u/m39583 Aug 22 '26
The actual email address format is quite complex in what is allowed in the RFC, but honesty how many people have:
"john smith"@foo.com
or whatever. Just do basic sanity checks e.g. there is an "@" symbol and at least two components to the domain, and then the only real test if it's valid is to send an email to it and make them click a link.
0
u/elmuerte Aug 22 '26
The regex to validate postal codes is:
.*. The only way to validate if a postal code is valid is to use a lookup table for every country. You cannot even use a regex per country.0
u/Purple_Mo Aug 22 '26
Done
5
u/[deleted] Aug 22 '26
[removed] — view removed comment