Validating inputted data from forms in Ruby on Rails can be at first be a challenging, there are no central form validation classes like there are in other web frameworks. Although Active Record is primarily used as an interface to a regional database it can be used for non-Database data validation using it’s ActiveModel::Validations component. In this example I will be validating posted data (Name, email address and message body) from a contact form.
Create our Contact Model
To get started, lets begin by creating the contact model that will contain the validation logic, run this command in your terminal:
Notice we are telling the generate command not to create any testing or migrations files, only the Contact model will be created in
Write our Models Logic
Open up the newly created contact model in your preferred text editor, rails has generated a basic model class for us to modify. The first issue is that it inherits Active Record::Base, as we are not going to interface with an actual database remove ‘< ActiveRecord::Base’ from the first line. We do on the other hand require the Validations, Conversion, and Naming classes, these can be included at the top.
Here is my final Contact Model in full:
As you can see from the validation rules we set the following validation rules for each attribute:
- name - Must be set
- address - Conforms with the giving regular expression, in this case a valid email address
- body - Maximum length of 500 characters
I have shown three methods (validates_presence_of, validates_format_of and validates_length_of) other examples include:
Details on these can be found on API Dock.
Using the Model in our Controller
Using the Contact model in the controller is fairly easy, I first created two methods; index and post, the first to display the form and the latter to handle posted data.
Using the Model in our View
Once the form has been posted it will validate the inputted values using the rules that we specified in the Contact model, for a full picture this is the view that I am using: