What is the "Elm Way" to validate form fields?

Thanks for the kind words! The way I’ve personally found best to approach forms is:

  • Treat the form like any other Elm program: save relevant state in Model, render it in view, update with update. My motto is: “forms are programs.” They aren’t special. Don’t go on a quest to find the magic formula to break them down into LEGO bricks that snap together—just write the program!
    • If the form is really small, anything more than elm-html is unlikely to justify its inherent cost of abstraction. If the form is really complex, a form-building library (or formulaic pattern) consistently seems to turn out to be incompatible with certain edge cases that are unique to this particular form. Then the thing that seemed helpful at first ends up being something I have to do contortions to work around.
    • Ever since realizing I could just write the program, handling edge cases—especially around interactions involving several different fields at once (typically the hardest part about forms)—is maximally easy because all the information I could possibly need is easily accessible right there in Model, and I’m in complete control of all the logic!
  • Really the only packages I reach for are things that are concerned with data (and not with the concept of “forms” at all), e.g. email validation functions.
  • For any user inputs that are going to be rendered, I always want to remember the original String the user entered (even if it’s going to be validated into a number) so I can render back to the user exactly what they typed into the field—regardless of whether it was valid. It’s a more frustrating user experience to type something and have it not even appear in the field (as if I hadn’t even pressed the key) compared to having it show up and then seeing an error message.
  • I also like to record some info in the Model about which fields are “in progress” and therefore not to be validated yet - e.g. if the user starts typing in the email field, don’t display a big red validation error right after they type the first letter because "r" isn’t a valid email address.

Hope that helps! :smiley:

17 Likes