Validating best practices, property vs dto, simple type vs object

programming practicesvalidation

Consider an application where adds an email address to his profile and submits it.

We have some dispute in our team over how to validate this email address. Some developers (including me) believe that we should validate this simple string via an extension method:

bool isValid = newEmail.IsEmail();

They argue that any validation mechanism other than a single method call would be overhead, and an anti-pattern (against KISS principal).

While others argue that this email should first be added to a new instance of UserEmail DTO, then that DTO should be passed to a the relevant validator:

UserEmail userEmail = new UserEmail() { Email = newEmail };
bool isValid = new UserEmailValidator().Validate(userEmail);

The second group argues that validating a single property makes no sense, because a property can't exist on its own. Thus we should always validate an object, not a property (I mean, value type properties, like strings and integers, etc.)

What advantages and disadvantages could each approach have?

Best Answer

It depends on your validation rules. Checking for a correctly formatted email address can be a simple method call. Checking that an email address actually exists, or that it is not already in use somewhere else requires a larger context that usually isn't appropriate as part of a simple field.

Where I disagree on in any case is wrapping it in a DTO instead of just passing the string straight into Validate(). If you eliminate the first line, the second solution suddenly doesn't look so horribly complex.