跳至內容 跳至搜尋
方法
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

驗證程式需要至少提供下列其中一項檢查。每項檢查都接受一個 procedure、值或符號,對應到一個函式

  • :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

以下檢查也可搭配 Proc 或符號,而符號對應至某個方法

  • :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)