跳到內容 跳到搜尋
方法
V

執行個體公開方法

validates_absence_of(*attr_names)

驗證指定的屬性為空白(由 Object#present? 定義)。

class Person < ActiveRecord::Base
  validates_absence_of :first_name
end

first_name 屬性必須在物件中且必須為空白。

組態選項

  • :message - 自訂錯誤訊息(預設為:「必須為空白」)。

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/absence.rb, line 28
def validates_absence_of(*attr_names)
  validates_with AbsenceValidator, _merge_attributes(attr_names)
end

validates_acceptance_of(*attr_names)

封裝想要驗證是否接受服務條款核取方塊(或類似同意書)的模式。

class Person < ActiveRecord::Base
  validates_acceptance_of :terms_of_service
  validates_acceptance_of :eula, message: 'must be abided'
end

如果資料庫欄位不存在,terms_of_service 屬性完全是虛擬的。只有在 terms_of_service 不為 nil 時才會執行此檢查。

組態選項

  • :message - 自訂錯誤訊息(預設為:「必須接受」)。

  • :accept - 指定視為已接受的值。也接受可能的數值陣列。預設值是陣列 [“1”, true],這使得它很容易與 HTML 核取方塊相關聯。如果您要驗證資料庫欄位,這應該設定為 true 或包含 true,因為屬性會在驗證前從 “1” 類型轉換為 true

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/acceptance.rb, line 108
def validates_acceptance_of(*attr_names)
  validates_with AcceptanceValidator, _merge_attributes(attr_names)
end

validates_comparison_of(*attr_names)

驗證指定屬性的值是否符合與另一個值、程序或屬性定義的所有比較。

class Person < ActiveRecord::Base
  validates_comparison_of :value, greater_than: 'the sum of its parts'
end

組態選項

  • :message - 自訂錯誤訊息(預設為:「比較失敗」)。

  • :greater_than - 指定值必須大於提供的數值。此選項的預設錯誤訊息為 _「必須大於 %{count}」_。

  • :greater_than_or_equal_to - 指定值必須大於或等於提供的數值。此選項的預設錯誤訊息為 _「必須大於或等於 %{count}」_。

  • :equal_to - 指定值必須等於提供的數值。此選項的預設錯誤訊息為 _「必須等於 %{count}」_。

  • :less_than - 指定值必須小於提供的數值。此選項的預設錯誤訊息為 _「必須小於 %{count}」_。

  • :less_than_or_equal_to - 指定值必須小於或等於提供的數值。此選項的預設錯誤訊息為 _「必須小於或等於 %{count}」_。

  • :other_than - 指定值不得等於提供的數值。此選項的預設錯誤訊息為 _「必須不為 %{count}」_。

此外,每個驗證器還支援下列預設選項::if:unless:on:allow_nil:allow_blank:strict 。有關更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

驗證器需要提供下列檢查之一。每個檢查都接受程序、值或對應於方法的符號

  • :greater_than

  • :greater_than_or_equal_to

  • :equal_to

  • :less_than

  • :less_than_or_equal_to

  • :other_than

例如

class Person < ActiveRecord::Base
  validates_comparison_of :birth_date, less_than_or_equal_to: -> { Date.today }
  validates_comparison_of :preferred_name, other_than: :given_name, allow_nil: true
end
# File activemodel/lib/active_model/validations/comparison.rb, line 85
def validates_comparison_of(*attr_names)
  validates_with ComparisonValidator, _merge_attributes(attr_names)
end

validates_confirmation_of(*attr_names)

封裝想要使用確認來驗證密碼或電子郵件地址欄位的模式。

Model:
  class Person < ActiveRecord::Base
    validates_confirmation_of :user_name, :password
    validates_confirmation_of :email_address,
                              message: 'should match confirmation'
  end

View:
  <%= password_field "person", "password" %>
  <%= password_field "person", "password_confirmation" %>

新增的 password_confirmation 屬性是虛擬的;它只存在於用於驗證密碼的記憶體中屬性中。為了達成此目的,驗證會新增存取器到確認屬性的模型中。

注意:此檢查只會在 password_confirmation 不為 nil 的情況下執行。若要需要確認,請務必為確認屬性新增存在檢查

validates_presence_of :password_confirmation, if: :password_changed?

組態選項

  • :message - 自訂錯誤訊息(預設為:「與 %{translated_attribute_name} 不符」)。

  • :case_sensitive - 尋找完全相符。非文字欄位會忽略此設定(預設為 true)。

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/confirmation.rb, line 75
def validates_confirmation_of(*attr_names)
  validates_with ConfirmationValidator, _merge_attributes(attr_names)
end

validates_exclusion_of(*attr_names)

驗證指定屬性的值不在特定的可列舉物件中。

class Person < ActiveRecord::Base
  validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
  validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
  validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
  validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
                         message: 'should not be the same as your username or first name'
  validates_exclusion_of :karma, in: :reserved_karmas
end

組態選項

  • :in - 值不應屬於其中一部分的項目可列舉物件。這可以提供為會傳回可列舉物件的程序、lambda 或符號。如果可列舉物件是數字、時間或日期時間範圍,則會使用 Range#cover? 執行測試,否則會使用 include?。使用程序或 lambda 時,會將正在驗證的執行個體傳遞為引數。

  • :within - :in 的同義詞(或別名)Range#cover?,否則會使用 include?

  • :message - 指定自訂錯誤訊息(預設為:「已保留」)。

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/exclusion.rb, line 44
def validates_exclusion_of(*attr_names)
  validates_with ExclusionValidator, _merge_attributes(attr_names)
end

validates_format_of(*attr_names)

驗證指定屬性的值是否為正確格式,依據提供的正規表示法。你可以要求屬性與正規表示法相符

class Person < ActiveRecord::Base
  validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
end

或者,你可以要求指定的屬性與正規表示法相符

class Person < ActiveRecord::Base
  validates_format_of :email, without: /NOSPAM/
end

你也可以提供會決定用於驗證屬性的正規表示法的程序或 lambda。

class Person < ActiveRecord::Base
  # Admin can have number as a first letter in their screen name
  validates_format_of :screen_name,
                      with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
end

注意:使用 \A\z 來相符字串的開頭和結尾,^$ 相符一行的開頭/結尾。

由於經常誤用 ^$,如果你在提供的正規表達式中使用這兩個錨定符號,你需要傳遞 multiline: true 選項。在多數情況下,你應該使用 \A\z

你必須傳遞 :with:without 作為選項。此外,兩者都必須是正規表達式或程序或 lambda,否則會引發異常。

組態選項

  • :message - 自訂錯誤訊息(預設為:「無效」)。

  • :with - 如果屬性符合的正規表達式將導致驗證成功。這可以提供為程序或 lambda 回傳正規表達式,且會在執行階段呼叫。

  • :without - 如果屬性不符合的正規表達式將導致驗證成功。這可以提供為程序或 lambda 回傳正規表達式,且會在執行階段呼叫。

  • :multiline - 如果你的正規表達式包含與字串開頭或結尾相對應的錨定符號,而不是與行開頭或結尾相對應的錨定符號,則設為 true。這些錨定符號為 ^$

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/format.rb, line 107
def validates_format_of(*attr_names)
  validates_with FormatValidator, _merge_attributes(attr_names)
end

validates_inclusion_of(*attr_names)

驗證指定屬性的值是否在特定可列舉物件中可用。

class Person < ActiveRecord::Base
  validates_inclusion_of :role, in: %w( admin contributor )
  validates_inclusion_of :age, in: 0..99
  validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
  validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
  validates_inclusion_of :karma, in: :available_karmas
end

組態選項

  • :in - 可用項目可列舉物件。這可以提供為程序、lambda 或傳回可列舉的符號。如果可列舉為數字、時間或日期時間範圍,則使用 Range#cover? 執行測試,否則使用 include?。當使用程序或 lambda 時,會將驗證中的執行個體傳遞為引數。

  • :within - :in 的同義詞(或別名)

  • :message - 指定自訂錯誤訊息(預設為:「未包含在清單中」)。

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/inclusion.rb, line 42
def validates_inclusion_of(*attr_names)
  validates_with InclusionValidator, _merge_attributes(attr_names)
end

validates_length_of(*attr_names)

驗證指定的屬性是否符合提供的長度限制。一次只能使用一個約束選項,但 :minimum:maximum 可以組合使用

class Person < ActiveRecord::Base
  validates_length_of :first_name, maximum: 30
  validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
  validates_length_of :fax, in: 7..32, allow_nil: true
  validates_length_of :phone, in: 7..32, allow_blank: true
  validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
  validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
  validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
  validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.'

  private
    def words_in_essay
      essay.scan(/\w+/)
    end
end

約束選項

  • :minimum - 屬性的最小大小。

  • :maximum - 屬性的最大大小。如果未與 :minimum 一起使用,預設允許 nil

  • :is - 屬性的確切大小。

  • :within - 指定屬性最小和最大大小的範圍。

  • :in - :within 的同義詞(或別名)。

其他選項

  • :allow_nil - 屬性可以為 nil;略過驗證。

  • :allow_blank - 屬性可以為空白;略過驗證。

  • :too_long - 如果屬性超過最大值,則顯示的錯誤訊息(預設為:「太長(最大長度為 %{count} 個字元)」)。

  • :too_short - 如果屬性小於最小值,則顯示的錯誤訊息(預設為:「太短(最小長度為 %{count} 個字元)」)。

  • :wrong_length - 如果使用 :is 方法,且屬性大小錯誤,則顯示的錯誤訊息(預設為:「長度錯誤(應為 %{count} 個字元)」)。

  • :message - 針對 :minimum:maximum:is 違規所使用的錯誤訊息。適當的 too_long/too_short/wrong_length 訊息的別名。

每個驗證器還支援一組預設選項::if:unless:on:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

別名為:validates_size_of
# File activemodel/lib/active_model/validations/length.rb, line 123
def validates_length_of(*attr_names)
  validates_with LengthValidator, _merge_attributes(attr_names)
end

validates_numericality_of(*attr_names)

透過嘗試使用 Kernel.Float 將其轉換為浮點數(如果 only_integerfalse)或套用正規表示式 /\A[+\-]?\d+\z/(如果 only_integer 設為 true),來驗證指定屬性的值是否為數字。Kernel.Float 值的精準度保證在 15 位數字以內。

class Person < ActiveRecord::Base
  validates_numericality_of :value, on: :create
end

組態選項

  • :message - 自訂錯誤訊息(預設為:「不是數字」)。

  • :only_integer - 指定值是否必須為整數(預設為 false)。

  • :only_numeric - 指定值是否必須為 Numeric 的執行個體(預設為 false)。預設行為是嘗試解析值(如果它是 String)。

  • :allow_nil - 如果屬性為 nil,則略過驗證(預設為 false)。請注意,對於 IntegerFloat 欄位,空字串會轉換為 nil

  • :greater_than - 指定值必須大於提供的數值。此選項的預設錯誤訊息為 _「必須大於 %{count}」_。

  • :greater_than_or_equal_to - 指定值必須大於或等於提供的數值。此選項的預設錯誤訊息為 _「必須大於或等於 %{count}」_。

  • :equal_to - 指定值必須等於提供的數值。此選項的預設錯誤訊息為 _「必須等於 %{count}」_。

  • :less_than - 指定值必須小於提供的數值。此選項的預設錯誤訊息為 _「必須小於 %{count}」_。

  • :less_than_or_equal_to - 指定值必須小於或等於提供的數值。此選項的預設錯誤訊息為 _「必須小於或等於 %{count}」_。

  • :other_than - 指定值必須與提供的數值不同。此選項的預設錯誤訊息為 _「必須與 %{count} 不同」_。

  • :odd - 指定值必須是奇數。此選項的預設錯誤訊息為 _「必須是奇數」_。

  • :even - 指定值必須是偶數。此選項的預設錯誤訊息為 _「必須是偶數」_。

  • :in - 檢查值是否在範圍內。此選項的預設錯誤訊息為 _「必須在 %{count} 中」_。

此外,每個驗證器還支援下列預設選項::if:unless:on:allow_nil:allow_blank:strict 。有關更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

以下檢查也可以提供程序或符號,對應於方法

  • :greater_than

  • :greater_than_or_equal_to

  • :equal_to

  • :less_than

  • :less_than_or_equal_to

  • :only_integer

  • :other_than

例如

class Person < ActiveRecord::Base
  validates_numericality_of :width, less_than: ->(person) { person.height }
  validates_numericality_of :width, greater_than: :minimum_weight
end
# File activemodel/lib/active_model/validations/numericality.rb, line 217
def validates_numericality_of(*attr_names)
  validates_with NumericalityValidator, _merge_attributes(attr_names)
end

validates_presence_of(*attr_names)

驗證指定的屬性不為空白(由 Object#blank? 定義)。

class Person < ActiveRecord::Base
  validates_presence_of :first_name
end

first_name 屬性必須在物件中,且不能為空白。

如果您要驗證布林欄位(實際值為 truefalse)的存在,您會想要使用 validates_inclusion_of :field_name, in: [true, false]

這是因為 Object#blank? 處理布林值的方式:false.blank? # => true

組態選項

  • :message - 自訂錯誤訊息(預設為: “不能空白”)。

每個驗證器也支援一組預設選項::if:unless:on:allow_nil:allow_blank:strict。如需更多資訊,請參閱 ActiveModel::Validations::ClassMethods#validates

# File activemodel/lib/active_model/validations/presence.rb, line 34
def validates_presence_of(*attr_names)
  validates_with PresenceValidator, _merge_attributes(attr_names)
end

validates_size_of(*attr_names)