1

I'm actually wondering what are the pros and cons of these two ways to handle client side validations / verifications.

Let's imagine an application where there is a contact form that needs these information:

  • An email address (with a specific format)
  • A postal address (with a specific postal code format)

I have in mind two ways to handle these format verifications:

At the form level

The "usual" way to handle this: we put some verifications based on user inputs and validate / invalidate the information.

Concretely, on the change (or submit, anyway) event of the input we verify the field value with some regexp and modify the current component state to display an error accordingly.

The "backend DDD" way

The idea is to rely on the following statement:

When creating an object, it should always be in a good and consistent shape so that you don't have to tweak for specific computations everywhere in the app

The idea is to enforce the verifications using schemas and to always rely on consistent objects that we don't have to tweak in multiple places like modifying one of its internal attributes by hand (implying multiple sanity verifications etc...).

In a concrete world, I would simply rely on a Email.create(rawInputValue) that may throw an error concerning a bad format exception or something like this. Email would be a class definition that owns information on how to build a valid email address.


After this bit of context, I'm wondering what are the pros / cons of these system? Which one do you use and why?

1 Answer 1

1

As you point out, the purpose of requring objects to always be in a consistent state is to avoid the need to re-validate the object's state outside the object whereever it is used - and thereby spreading the knowledge of what an e-mail address is all throughout the code base (DRY).

But this really just makes sense if you have an actual model that does something with the e-mail address. If your app is merely forwarding the address to the backend, there may not be a need for a dedicated e-mail object at all. You can simply have a function that validates the address and shows or hides an error message.

If you do further processing in the frontend, then an e-mail class might make sense. Of course, having an invalid e-mail address may actually be a valid state of your model - working with invalid inputs is simply part of the domain in user-facing systems.

But whatever you decide to be a valid model state, you should not allow invalid models to exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.