Validations

Learn about why we use validations and how to implement them in Rails.

If you start up the application now and create a new pet, you will notice that you can provide any input to each of the fields. You can even leave them all blank and a new pet will still be created.

You want to impose certain restrictions on what you consider a valid pet. For example, a pet must have a name, and its description must exceed a minimum character count. To impose these restrictions, we use validations.

Validations

Adding validation to model

To add validation into your application you will open the app/models/pet.rb file and add the following lines to your Pet model class:

validates :name, presence: true
validates :description, length: {minimum: 10}

These lines will ensure that the name entry has a value and description is at least 10 characters. If any of these restrictions are not met, the new pet creation will fail.

Get hands-on with 1400+ tech skills courses.