DEV Community

Cover image for Validations in Ruby on Rails
acw0415
acw0415

Posted on

Validations in Ruby on Rails

Validations are basically used to check and see if the data that is sent through your application is what you expected it to be.

You can basically think of it like a data filter, and there are many validation helpers you can use. Here are a few that I find useful:

class Teenager < ApplicationRecord
  validates :age, comparison: { greater_than_or_equal_to:13,
less_than_or_equal_to: 19}
end

Enter fullscreen mode Exit fullscreen mode


this is used to compare the data to parameters that you set. In the example above we are validating if someone is considered a teenager by comparing the data we get to the parameters set and if the integer is between 13 and 19 it will pass the validation.

class Salsa < ApplicationRecord
  validates :spice, inclusion: { in: %w(mild medium hot),
    message: "%{value} is not a valid spice level" }
end
Enter fullscreen mode Exit fullscreen mode


this is used to give a specific piece of data that must be included. In the example above the data enter must include mild, medium, or hot or it will not pass the validation. (a side note: the %w(data) used above is the same as [data] in ruby.)

class EmployeeDinner < ApplicationRecord
  validates :name, length: { minimum: 2 }
  validates :employee_number, length: { is: 9 }
  validates :menu, length: { maximum: 1000 }
  validates :times_attended, length: { in: 1..15 }

end

Enter fullscreen mode Exit fullscreen mode


this is used to give a specific length for whatever you are validating. In the example above the name has a minimum of 2 so the string must be longer than 2 characters, the employee_number is setting a specific value of 9 so it cannot be anything more or less that 9 characters, the menu is setting a maximum character limit of 1000, and times_attended is giving a range of anywhere between 1 and 15.

There are many different options for validations and they are all useful and unique it is worth taking the time to learn what each of them can do. I have only included 3 here, but there are many more. I have included a link below that goes over validations in far more detail. Hope this is helpful!

source: https://guides.rubyonrails.org/active_record_validations.html

Top comments (0)