Rails Validations

  • Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.

Confirmation

class User < ApplicationRecordvalidates :email, confirmation: trueend
<%= text_field :user, :email %><%= text_field :user, :email_confirmation %>
class User < ApplicationRecordvalidates :email, confirmation: truevalidates :email_confirmation, presence: trueend

Exclusion

class Profile < ApplicationRecordvalidates :username, exclusion: { in: %w(username1 username2 username3), message: “%{value} has already been taken.” }end

Format

class Plan < ApplicationRecordvalidates :plan_type, format: { with: /\A[a-zA-Z]+\z/, message: “Plans can only inlude letters”}end

Length

class User < ApplicationRecordvalidates :name, length: { minimum: 5 } # sets a minimumvalidates :bio, length: { maximum: 500 } # sets a maximumvalidates :handle, length: { in: 5..16 } # provide a rangeend
  • wrong_length
  • too_long
  • too_short
class User < ApplicationRecordvalidates :bio, length: { maximum: 800, too_long: “%{count} characters is the maximum.” }end

Presence

class User < ApplicationRecordvalidates :name, :email, presence: trueend
class Article < ApplicationRecordbelongs_to :uservalidates :user, presence: true # looks for a user_id field on the articleend
class User < ApplicationRecordhas_many :articles, inverse_of: :userend

Uniqueness

class User < ApplicationRecordvalidates :username, uniqueness: true, { message: “Username already taken” }end

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store