invalid?

invalid?(context = nil)
Instance Public methods

Performs the opposite of valid?. Returns true if errors were added, false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
class Person
  include ActiveModel::Validations
 
  attr_accessor :name
  validates_presence_of :name
end
 
person = Person.new
person.name = ''
person.invalid? # => true
person.name = 'david'
person.invalid? # => false

Context can optionally be supplied to define which callbacks to test against (the context is defined on the validations using :on).

1
2
3
4
5
6
7
8
9
10
class Person
  include ActiveModel::Validations
 
  attr_accessor :name
  validates_presence_of :name, on: :new
end
 
person = Person.new
person.invalid?       # => false
person.invalid?(:new) # => true
doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.