Ruby on Rails


ActiveRecord Validations 3.0–5.0

1.0
1.1
1.2
2.0
2.3
3.0
3.1
3.2
4.0
4.1
4.2
5.0

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 10
    class Person < ApplicationRecord
      validates :name, length: { minimum: 2 }
      validates :bio, length: { maximum: 500 }
      validates :password, length: { in: 6..20 }
      validates :registration_number, length: { is: 6 }
    end
    

    The possible length constraint options are:

    • :minimum - The attribute cannot have less than the specified length.
    • :maximum - The attribute cannot have more than the specified length.
    • :in (or :within) - The attribute length must be included in a given interval. The value for this option must be a range.
    • :is - The attribute length must be equal to the given value.
  • 6

    This helper validates that the specified attributes are not empty.

    class Person < ApplicationRecord
      validates :name, presence: true
    end
    
    Person.create(name: "John").valid? # => true
    Person.create(name: nil).valid? # => false
    

    You can use the absence helper to validate that the specified attributes are absent. It uses the present? method to check for nil or empty values.

    class Person < ApplicationRecord
      validates :name, :login, :email, absence: true
    end
    

    Note: In case the attribute is a boolean one, you cannot make use of the usual presence validation (the attribute would not be valid for a false value). You can get this done by using an inclusion validation:

    validates :attribute, inclusion: [true, false]
    
  • 5

    Validate that an attribute's value matches a regular expression using format and the with option.

    class User < ApplicationRecord
      validates :name, format: { with: /\A\w{6,10}\z/ }
    end
    

    You can also define a constant and set its value to a regular expression and pass it to the with: option. This might be more convenient for really complex regular expressions

    PHONE_REGEX = /\A\(\d{3}\)\d{3}-\d{4}\z/
    validates :phone, format: { with: PHONE_REGEX }
    

    The default error message is is invalid. This can be changed with the :message option.

    validates :bio, format: { with: /\A\D+\z/, message: "Numbers are not allowed" }
    

    The reverse also replies, and you can specify that a value should not match a regular expression with the without: option

Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about ActiveRecord Validations? Ask Question

Topic Outline