- A
- C
- V
實例公開方法
attribute_method?(attribute) 連結
如果 `attribute` 是屬性方法,則回傳 `true`,否則回傳 `false`。
class Person
include ActiveModel::Validations
attr_accessor :name
end
User.attribute_method?(:name) # => true
User.attribute_method?(:age) # => false
clear_validators!() 連結
清除所有驗證程式的檢查程式。
請注意,這會清除已用於檢查 `validates_with` 和 `validate` 方法模型的任何內容。它會清除依照 `validates_with` 呼叫建立的驗證程式的檢查程式和依照 `validate` 呼叫設定的回呼。
class Person
include ActiveModel::Validations
validates_with MyValidator
validates_with OtherValidator, on: :create
validates_with StrictValidator, strict: true
validate :cannot_be_robot
def cannot_be_robot
errors.add(:base, 'A person cannot be a robot') if person_is_robot
end
end
Person.validators
# => [
# #<MyValidator:0x007fbff403e808 @options={}>,
# #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
# #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
# ]
如果執行 `Person.clear_validators!` ,然後檢查這個類別有哪些驗證程式的檢查程式,會取得
Person.validators # => []
此外,會清除已由 `validate :cannot_be_robot` 設定的回呼,因此
Person._validate_callbacks.empty? # => true
validate(*args, &block) 連結
新增驗證方法或區塊到類別。當覆寫 `validate` 實例方法過於龐大並且您正在尋找更明確的驗證宣告時,這會很有用。
這可以用指向方法的符號完成
class Comment
include ActiveModel::Validations
validate :must_be_friends
def must_be_friends
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
end
end
使用區塊,並傳遞目前要驗證的記錄
class Comment
include ActiveModel::Validations
validate do |comment|
comment.must_be_friends
end
def must_be_friends
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
end
end
或使用區塊,其中 `self` 指向目前要驗證的記錄
class Comment
include ActiveModel::Validations
validate do
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
end
end
請注意,驗證方法的回傳值無關緊要。無法終止驗證回呼鏈。
選項
-
:on
- 指定此驗證項處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `on: :create` 或 `on: :custom_validation_context` 或 `on: [:create, :custom_validation_context]) -
:except_on
- 指定此驗證項不處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `except: :create` 或 `except_on: :custom_validation_context` 或 `except_on: [:create, :custom_validation_context]) -
:if
- 指定方法、程序或字串以呼叫來判斷是否應該執行驗證(例如,if: :allow_validation
或if: Proc.new { |user| user.signup_step > 2 }
)。此方法、程序或字串應傳回或評估為true
或false
值。 -
:unless
- 指定方法、程序或字串以呼叫來判斷是否不應該執行驗證(例如,unless: :skip_validation
或unless: Proc.new { |user| user.signup_step <= 2 }
)。此方法、程序或字串應傳回或評估為true
或false
值。
備註:針對同一個方法呼叫 validate
好幾次會覆寫先前的定義。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validations.rb, line 160 def validate(*args, &block) options = args.extract_options! if args.all?(Symbol) options.each_key do |k| unless VALID_OPTIONS_FOR_VALIDATE.include?(k) raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{VALID_OPTIONS_FOR_VALIDATE.map(&:inspect).join(', ')}. Perhaps you meant to call `validates` instead of `validate`?") end end end if options.key?(:on) options = options.merge(if: [predicate_for_validation_context(options[:on]), *options[:if]]) end if options.key?(:except_on) options = options.dup options[:except_on] = Array(options[:except_on]) options[:unless] = [ ->(o) { (options[:except_on] & Array(o.validation_context)).any? }, *options[:unless] ] end set_callback(:validate, *args, options, &block) end
validates(*attributes) 連結
這個方法是預設驗證器和以「Validator」結尾的任何自訂驗證器類別的捷徑。請注意,自訂驗證器類別(如 PresenceValidator)可以在特定類別內覆寫 Rails 預設驗證器,取代其位置。
使用預設 Rails
驗證器的範例
validates :username, absence: true
validates :terms, acceptance: true
validates :password, confirmation: true
validates :username, exclusion: { in: %w(admin superuser) }
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :age, inclusion: { in: 0..9 }
validates :first_name, length: { maximum: 30 }
validates :age, numericality: true
validates :username, presence: true
validates 方法的強大之處在於可以在單一呼叫中同時使用自訂驗證器和預設驗證器來執行特定屬性的驗證。
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, (options[:message] || "is not an email") unless
/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i.match?(value)
end
end
class Person
include ActiveModel::Validations
attr_accessor :name, :email
validates :name, presence: true, length: { maximum: 100 }
validates :email, presence: true, email: true
end
Validator
類別也可能存在於正在驗證的類別中,允許視需要包含自訂驗證器模組。
class Film
include ActiveModel::Validations
class TitleValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, "must start with 'the'" unless /\Athe/i.match?(value)
end
end
validates :name, title: true
end
此外,驗證器類別可以屬於其他命名空間,仍在任何類別中使用。
validates :name, :'film/title' => true
驗證器雜湊也可以使用捷徑形式來處理正規表示式、範圍、陣列和字串。
validates :email, format: /@/
validates :role, inclusion: %w(admin contributor)
validates :password, length: 6..20
使用捷徑模式時,範圍和陣列會傳遞至驗證器的初始化模組作為 options[:in]
,而其他型別(包括正規表示式和字串)則傳遞為 options[:with]
。
還有一系列選項可以與驗證器一同使用
-
:on
- 指定此驗證項處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `on: :create` 或 `on: :custom_validation_context` 或 `on: [:create, :custom_validation_context]) -
:except_on
- 指定此驗證項不處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `except: :create` 或 `except_on: :custom_validation_context` 或 `except_on: [:create, :custom_validation_context]) -
:if
- 指定方法、程序或字串以呼叫來判斷是否應該執行驗證(例如,if: :allow_validation
或if: Proc.new { |user| user.signup_step > 2 }
)。此方法、程序或字串應傳回或評估為true
或false
值。 -
:unless
- 指定方法、程序或字串以呼叫來判斷是否不應該執行驗證(例如,unless: :skip_validation
或unless: Proc.new { |user| user.signup_step <= 2 }
)。此方法、程序或字串應傳回或評估為true
或false
值。 -
:allow_nil
- 如果屬性為nil
,則略過驗證。 -
:allow_blank
- 如果屬性為空白,則略過驗證。 -
:strict
- 如果:strict
選項設為 true,則會引發ActiveModel::StrictValidationFailed
,而不是新增錯誤。:strict
選項也可以設為任何其他例外。
範例
validates :password, presence: true, confirmation: true, if: :password_required?
validates :token, length: { is: 24 }, strict: TokenLengthException
最後,選項 :if
、:unless
、:on
、:allow_blank
、:allow_nil
、:strict
和 :message
可以提供給單一特定驗證器,作為雜湊
validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validations/validates.rb, line 111 def validates(*attributes) defaults = attributes.extract_options!.dup validations = defaults.slice!(*_validates_default_keys) raise ArgumentError, "You need to supply at least one attribute" if attributes.empty? raise ArgumentError, "You need to supply at least one validation" if validations.empty? defaults[:attributes] = attributes validations.each do |key, options| key = "#{key.to_s.camelize}Validator" begin validator = const_get(key) rescue NameError raise ArgumentError, "Unknown validator: '#{key}'" end next unless options validates_with(validator, defaults.merge(_parse_validates_options(options))) end end
validates!(*attributes) 連結
這個方法用於定義無法由最終使用者糾正的驗證,並被視為例外。因此,在 bang 或 :strict
選項設為 true
的情況下定義的每個驗證器在驗證失敗時,總是會引發 ActiveModel::StrictValidationFailed
,而不是新增錯誤。有關驗證本身的更多資訊,請參閱 validates
。
class Person
include ActiveModel::Validations
attr_accessor :name
validates! :name, presence: true
end
person = Person.new
person.name = ''
person.valid?
# => ActiveModel::StrictValidationFailed: Name can't be blank
validates_each(*attr_names, &block) 連結
根據區塊驗證每個屬性。
class Person
include ActiveModel::Validations
attr_accessor :first_name, :last_name
validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
record.errors.add attr, "starts with z." if value.start_with?("z")
end
end
選項
-
:on
- 指定此驗證項處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `on: :create` 或 `on: :custom_validation_context` 或 `on: [:create, :custom_validation_context]) -
:except_on
- 指定此驗證項不處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `except: :create` 或 `except_on: :custom_validation_context` 或 `except_on: [:create, :custom_validation_context]) -
:allow_nil
- 如果屬性為nil
,則略過驗證。 -
:allow_blank
- 如果屬性為空白,則略過驗證。 -
:if
- 指定一個方法、程序或字串來呼叫以判斷是否應執行驗證 (例如:if: :allow_validation
或if: Proc.new { |user| user.signup_step > 2 }
)。方法、程序或字串應該回傳或評估為true
或false
值。 -
:unless
- 指定方法、程序或字串以呼叫來判斷是否不應該執行驗證(例如,unless: :skip_validation
或unless: Proc.new { |user| user.signup_step <= 2 }
)。此方法、程序或字串應傳回或評估為true
或false
值。
validates_with(*args, &block) 連結
將紀錄傳遞給所指定的類別或類別,並允許他們基於更複雜的條件增加錯誤。
class Person
include ActiveModel::Validations
validates_with MyValidator
end
class MyValidator < ActiveModel::Validator
def validate(record)
if some_complex_logic
record.errors.add :base, 'This record is invalid'
end
end
private
def some_complex_logic
# ...
end
end
你也可以傳多個類別,像這樣
class Person
include ActiveModel::Validations
validates_with MyValidator, MyOtherValidator, on: :create
end
validates_with
沒有預設錯誤訊息。你必須手動將錯誤新增到驗證類別中的紀錄錯誤集合。
若要實作驗證方法,你必須定義一個 record
參數,這是要驗證的紀錄。
設定選項
-
:on
- 指定此驗證項處於作用中的情境。預設於所有驗證情境執行 `nil`。您可以傳遞符號或符號陣列。(例如 `on: :create` 或 `on: :custom_validation_context` 或 `on: [:create, :custom_validation_context]) -
:if
- 指定一個方法、程序或字串來呼叫以判斷是否應執行驗證 (例如:if: :allow_validation
或if: Proc.new { |user| user.signup_step > 2 }
)。方法、程序或字串應該回傳或評估為true
或false
值。 -
:unless
- 指定方法、程序或字串以呼叫來判斷是否不應該執行驗證(例如,unless: :skip_validation
或unless: Proc.new { |user| user.signup_step <= 2 }
)。此方法、程序或字串應傳回或評估為true
或false
值。 -
:strict
- 指定驗證是否應為嚴格。有關更多資訊,請參閱ActiveModel::Validations#validates!
。
如果你傳遞任何額外的設定選項,它們將會傳遞給類別並可用為 options
class Person
include ActiveModel::Validations
validates_with MyValidator, my_custom_key: 'my custom value'
end
class MyValidator < ActiveModel::Validator
def validate(record)
options[:my_custom_key] # => "my custom value"
end
end
# File activemodel/lib/active_model/validations/with.rb, line 88 def validates_with(*args, &block) options = args.extract_options! options[:class] = self args.each do |klass| validator = klass.new(options.dup, &block) if validator.respond_to?(:attributes) && !validator.attributes.empty? validator.attributes.each do |attribute| _validators[attribute.to_sym] << validator end else _validators[nil] << validator end validate(validator, options) end end
validators() 連結
列出所有用來驗證模型的驗證器,這些驗證器是使用 validates_with
方法。
class Person
include ActiveModel::Validations
validates_with MyValidator
validates_with OtherValidator, on: :create
validates_with StrictValidator, strict: true
end
Person.validators
# => [
# #<MyValidator:0x007fbff403e808 @options={}>,
# #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
# #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
# ]
validators_on(*attributes) 連結
列出用來驗證特定屬性的所有驗證器。
class Person
include ActiveModel::Validations
attr_accessor :name, :age
validates_presence_of :name
validates_inclusion_of :age, in: 0..99
end
Person.validators_on(:name)
# => [
# #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
# ]