Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

8.5 Short-Form Validation

The validates method identifies an attribute and accepts options that correspond to the validators we’ve already covered in the chapter. It lets you group all the validations that apply to a single field together and can tighten up your model code nicely as well as make it more readable.

validates :username, presence: true,
  format: { with: /[A-Za-z0-9]+/ },
  length: { minimum: 3 },
  uniqueness: true

The following options are available for use with the validates method.

  • absence: true Alias for validates_absence_of. Supply additional options by replacing true with a hash.

    validates :unwanted, absence: { message: "should not have been set" }
  • acceptance: true Alias for validates_acceptance_of, typically used with check boxes that indicate acceptance of terms. Supply additional options by replacing true with a hash.

    validates :terms, acceptance: { message: 'must be accepted' }
  • confirmation: true Alias for validates_confirmation_of, typically used to ensure that email and password confirmation fields match up correctly. Supply additional options by replacing true with a hash.

    validates :email, confirmation: { message: 'is required' }
  • exclusion: { in: [1,2,3] } Alias for validates_exclusion_of. If your only option is the array to exclude against, you can shorten the syntax further by supplying an array as the value.

    validates :username, exclusion: %w(admin superuser)
  • format: { with: /.*/ } Alias for validates_format_of. If your only option is the regular expression, you can shorten the syntax further by making it the value like:

    format: /[A-Za-z0-9]+/
  • inclusion: { in: [1,2,3] } Alias for validates_inclusion_of. If your only option is the inclusion array, you can shorten the syntax further by making the array the value.

    validates :gender, inclusion: %w(male female)
  • length: { minimum: 0, maximum: 1000 } Alias for validates_length_of. If your only options are minimum and maximum lengths, you can shorten the syntax further by supplying a Ruby range as the value.

    validates :username, length: 3..20
  • numericality: true Alias for validates_numericality_of. Supply additional options by replacing true with a hash.

    validates :quantity, numericality: { message: 'should be a number' }
  • presence: true Alias for validates_presence_of. Supply additional options by replacing true with a hash.

    validates :username, presence: { message: 'is missing (How do
             you expect to login without it?)' }
  • uniqueness: true Alias for validates_uniqueness_of. Supply additional options by replacing true with a hash.

    validates :screenname, uniqueness: { message: "was nabbed by
             someone else first" }
  • + Share This
  • 🔖 Save To Your Account