Rails — The Importance of Validations

Courtney Wilson
2 min readOct 12, 2021

So in making my project for phase 4, Rails, I had almost forgot to include validations. Validations are a super important but fairly simple process. They are special methods that go in the models that will prevent incorrect data from being saved. They will make sure that a user provides a valid email address (checking for the @ symbol), ensure any data fields are filled in, keep a number range in check, confirm the length of a password, etc.

How do we go about doing this? First, we have to decide what we want to validate. What info is crucial and needs to be included to be saved to the database? For instance, the presence of a username. We don’t want just anyone to sign in without a username, right? So we go to the model and validate our username. There are a couple different ways we can validate, so check it out -

Validating our username.

Here, we are calling to validate our attribute (data point) of our username. We are saying that the presence of a username has to be true. So our data cannot save, in this case, we cannot log in, without a username.

There are so many different validations we can perform. And we format them in different ways. Check out the following code and read along below to get an idea of what each line is validating.

This code simulates a signup. The first validation is combining both the presence and uniqueness of a username, meaning that the username has to be present and it has to be unique. This will prevent more than one user having the same username. The next validation displays another way of formatting the method. This line validates the presence of both a password and email address. The last line will validate the length of the password, so it can’t be shorter than 7 characters, nor can it be longer than 32 characters.

Every attribute can be validated and there are so many different methods you can use. You can check out the documentation here and find a method that works for your needs. Section two starts explaining many of the different validation helpers and how they are used. You can validate a boolean on whether or not a user has agreed to terms of service, the format (whether or not special characters are accepted), and so much more.

--

--