Custom Validations and When to use them
Validations are a powerful tool for developers to implement to control the data before it’s inputted & stored in the database. Without validations, our data can get really out of hand.
Imagine an application without proper validations — we’d have cases where an account is created without a username, a shipping address with no address, an email address that is missing the @ sign, etc. Our data quickly becomes useless, and we’d quickly have an ineffective application.
Having these validations in place allows the developers to store useful (and valid) data. In addition, Rails makes them easy to use, and Active Records provides built-in helpers for common needs, as listed above.
But what if the scope of our needs goes beyond the built-in helpers?
Want to read this story later? Save it in Journal.
That’s where custom validations come in. As a beginner developer, I have yet to come across a project where I’ve had to use custom validations. In fact, the concept of validations was only introduced to me just recently, working with built-in helpers such as presence (validates that the specified attributes are not empty), uniqueness (validates that the attribute’s value is unique right before the object gets saved into the database), and numericality (validates that your attributes have only numeric values).
The idea of creating our own custom validations intrigued me. But how do we create it, and what kind of custom validations can we implement?
How Validations Work
Before we dive into writing custom validations, it’s important to determine when & how validations work.
When a developer first creates an object (using the new method, for example), the object is created but it still hasn’t been saved to the database yet — only once it’s saved will it be stored into the appropriate database table. Typically, validations are run before the data is saved or updated.
As mentioned before, Active Record provides many built-in validation helpers that we can use directly in our class models. These helpers satisfies some of our most common needs.
In the example above, we’re setting two validations in our Duck model. As the name implies, these validations check that a name & description exists before saving the information into the database. We wouldn’t want a duck with no name in our database!
Writing Custom Validation Methods
Setting up our custom validations is very similar to setting up our built-in helpers. Using our Duck Model, let’s set up a custom validation where our ducks can’t be named Donald:
Notice a subtle difference? With our custom validations, we drop the “s” on validates! We use our validate class method, and pass in the symbol for our validation methods’ name (:name_can_not_be_donald).
Contrary to our built-in helpers, Active Record does not recognize our custom methods (Active Record is magical, but not that magical).
Next, we have to define our method. Our custom method will typically contain a conditional, or “if” statement, that will determine the validity of our data. In this simple example, we are checking to see whether the name that is inputted for the duck is equal to “donald”.
As seen in our snippet above, our conditional checks to see if the instance of the duck’s name is equal to “donald”. If it is, we hit our line of code which displays our custom message of, “There can only be one Donald Duck!”.
Our code uses a Rails built-in method for working with the errors collection and inquiring about the validity of objects. The “add” method takes in two parameters and allows us to create a custom message that are related to our particular attribute in our first parameter.
Pretty cool right? Not only are we able to create our own validations to control the data that is saved into our database, but we can also set a custom message for our users to see — otherwise they won’t know why they’re receiving an error if they don’t pass one of our validations!
It’s important to note that there is an alternative way to set up custom validations in our models is writing your own custom validators. While it functions similarly to the custom methods approach above, the approach is a tad different. Instead of writing our own custom method, we would implement the validate method and call it by using the validates_with method. Again, both ways perform similarly and I recommend reading up on both approaches to find the one that’s most suitable for you!
User side Implementation
We’re missing a key component. While it’s great to set up our validations in our models to act as a barrier between our models & our database, we haven’t set up the user side of the validation. The custom message is set in our method, but where does it appear?
Currently, if a user tried to name their duck “donald” they wouldn’t get the message and just be left in limbo. That’s not helpful at all!
So when should our error appear? If I were the user, I’d probably want to be notified as soon as I submit my duck’s name via a web form.
Rails provides some helpful built-in methods to display error messages, but I prefer the handy Flash method, which is a Rails method with which you can render saved messages and information in the next full-page reload of your browser & clear it right after.
With our Model set, we’ll need to define our Flash messages in our controller & views.
In our controller, our flash[:errors] is set to display our error messages if our validations were triggered, redirecting our users back to the page where they were attempting to create the new duck.
Finally, in our view page, we would show our custom message (along with any other validations, custom or built-in) if needed. Our users are now aware of any issues they encounter, and we’re able to control our stored data.
To read more on flash messages, I recommend checking out the documentation at Ruby Guides: https://www.rubyguides.com/2019/11/rails-flash-messages/
Validations are a wonderful tool for developers to control the data before it gets saved into the database. Without validations, our database will contain inconsistent data and plenty of unwelcome surprises.
While Rails provide a welcome amount of built in validations, there will be times where custom validations will be needed.
By writing custom methods in our models and use flash messages in our view, we’re able to keep a secure database and running an effective app for our users.
Ruby on Rails: Active Record Validations and Callbacks
Ruby on Rails Guides: Active Record Validations and Callbacks
During the normal operation of a Rails application objects may be created, updated, and destroyed. Active Record…
Ruby on Rails: Active Record Validations
More from Journal
There are many Black creators doing incredible work in Tech. This collection of resources shines a light on some of us: