Complex Email Address Validation

Tag: validation Author: kemao Date: 2009-07-15

I need to validate an email address which will be transmitted to several possible state and federal agencies, each which may reject the entire form if the email address does not meet their validation requirements. (Some reject perfectly valid characters while others don't validate it at all and still others don't even support an email address field)

My choices are:

  1. Create a single address validator which is incredibily strict.
  2. Create a very loose validator for the main entry then revalidate with a custom validator for each agency as need dictates prior to transmitting each form.
  3. Something I haven't thought of?

I'm leaning toward the second, even though it will mean more work because it won't force the user to create an additional email account unless a particular agency refuses to accept their normal one.

I know this is really the agency's problem if they reject a perfectly legal email address but requests to fix these kind of things take a while to get answered and when something goes wrong customers don't blame the agency, they blame the software. (Even if its their own typographical error)

Best Answer

Second option is the definite choice: one huge validator (be it code, regex, rule-based, whatever) will be a nightmare to support and extend. Moreover, it's 20% less SOLID in that it violates S and O.

Other Answer1

I prefer also the second one, because if an agency changes its validation requirements, it is easier to modify your code.

Furthermore, it is quite easier to add new agencies.

Other Answer2

I would definitely go for the second option. Have a very generic validator for an initial check. Then smaller, separate validators for each agency. More work up front, but much easier to maintain. Like Oxymoron said, if an agency changed their valid e-mail requirements, you only change the one validator. It's also minimal to add new agencies or remove agencies. It works on the low coupling, high cohesion principle.