« Back to Blog

Form Validation vs. Correction in Rails

Developers have a great deal of control over a web user’s experience, and when it comes to validating input forms, opportunities to make things smoother for the user are something every good developer should think about.

For example, I am working on a project right now where users can enter the URL of a link into the database-driven content. In order for the link to work correctly on the front end, it has to have the “http://” prefix on it. And as we all know, it would be folly to assume that every user who submits a link will append the correct prefix.

The easiest solution, and the one I see most often, is to validate the format of the URL and return an error if the user left out the http:// at the beginning of the URL, prompting them to correct their own formatting before they can submit the form. That would look something like this (in the model):


In my opinion, a better option is to validate and correct the user’s input if it lacks the proper formatting, using a simple Ruby method (again, in the model):


Then you add a before_save helper which fires off the method before the model is saved:


This way, the user can format the link correctly or incorrectly and it won’t matter. The form will still submit, and the link will be properly formatted behind the scenes. The solution is much better from the user’s perspective, because it doesn’t require a second round of corrections or annoying error messages.

Lastly, a little refactoring. You don’t actually even need the before_save helper if you do it this way:


So, a little extra thought at the developer level makes for a much smoother experience at the user level, and the database gets nicely formatted data every time.

Tagged: ruby, rails, ruby on rails, validation, correction, forms, user experience

Add a Comment





simple_captcha.jpg Type the letters from the image.