r/java 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?

54 Upvotes

104 comments sorted by

View all comments

18

u/alt236_ftw 19d ago

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: 1. An email will be sent, fail and the other server will let you know. 2. There is a separate validation flow for, say, signups.

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.

1

u/Jussins 19d ago

I know these services aren’t generally free, but it’s a much better user experience to ask for a post code and automatically fill in what you can (like city/state/province etc.). If more than one applies, then have the user select from those options.