Form Validation Done Right
Almost everything you’ve been told about form validation is a bad practice. Why? Because it tells you to validate the form instead of the model. That’s backward.
Let me ask you an unsettling question: “is the field required because the form says so or because it’s a business model requirement? Would the model be invalid even if we never displayed that field?”
Of course we have to express the required rule in the UI. We must tell the user the value is missing and (perhaps) force the user to enter it. But the value is still required whether the field appears on the form or not. And that is just the start of our troubles.
We’d like to tell the user if the whole model is valid. We’d want to block certain operations if the model is invalid anywhere. We’d love to display a list of all invalid fields with links the user can click to navigate to the page where they can fix the problem. We’d prefer to find, document, and maintain all of the validation rules in one place and write unit tests for them. We’d like to apply the same rules on both server and client without writing them twice. None of that is possible with validations embedded in forms.
This talk is a follow-up to my impassioned argument for Template Driven forms at last year’s ngConf (https://www.youtube.com/watch?v=L7rGogdfe2Q). Many folks (incorrectly) try to argue that validation is a weakness of Template Driven forms. I will show that Angular validation, as taught, is a weakness of Reactive forms as well. What we need is a model-driven validation library that integrates with both modalities, one that is powerful and easy to use in the scenarios you wish you could handle today.
Of course I’ll show you an open-source validation library that we wrote and have used at our biggest Angular client for the last 3 years.