Form validation is one part of web development that I’ve never really enjoyed. Part of what I love about programming is getting to spend my day solving challenging problems; form validation feels more like a mundane chore.
Back in 2016, I started developing an app that used Facebook’s React framework, and it wasn’t long before I found the need to do form validation. I spent some time Googling and reading through other people’s approaches but wasn’t really satisfied with anything I found, so I decided to take a stab at it myself.
One of my goals was to come up with an approach that was composable. I wanted to be able to define a collection of form requirements that could be applied to form fields as needed.
Another goal was to keep as much code out of my Components as possible. One of my complaints about the React framework is that it doesn’t do as much as it could to help developers separate business-logic from presentation-level code. I like to keep my Components as light as possible, so I wanted to make sure that my form validation approach didn’t rely on adding a lot of clutter to them.
Finally, I wanted to have all of the validation error text strings defined in one place. I prefer this for a few reasons: First, it makes it really easy to find the code if/when you need to go back and change the content. Second, if I ever need to support multiple languages, it will be really simple to go in and replace all my hardcoded strings with localized strings. Finally, it makes it very easy to reuse error strings for multiple form fields.
In October of 2016, I published a post describing my approach to satisfying the goals listed above. Since then, I’ve received many requests for a full working demo. Here it is:
Let me know what you think in the comments.