2015-01-14 01:22:13 -05:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
2014-12-23 17:32:50 -05:00
2012-11-29 17:45:58 -05:00
Active Record Validations
=========================
2012-10-17 09:15:55 -04:00
2012-11-29 17:45:58 -05:00
This guide teaches you how to validate the state of objects before they go into
the database using Active Record's validations feature.
2012-10-17 09:15:55 -04:00
2012-11-29 17:25:02 -05:00
After reading this guide, you will know:
2012-10-17 09:15:55 -04:00
2012-12-07 12:50:09 -05:00
* How to use the built-in Active Record validation helpers.
* How to create your own custom validation methods.
* How to work with the error messages generated by the validation process.
2012-10-17 09:15:55 -04:00
--------------------------------------------------------------------------------
Validations Overview
--------------------
2012-11-29 18:24:08 -05:00
Here's an example of a very simple validation:
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-11-29 18:24:08 -05:00
validates :name, presence: true
end
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Person.create(name: "John Doe").valid? # => true
Person.create(name: nil).valid? # => false
```
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
As you can see, our validation lets us know that our `Person` is not valid
without a `name` attribute. The second `Person` will not be persisted to the
database.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Before we dig into more details, let's talk about how validations fit into the
big picture of your application.
### Why Use Validations?
Validations are used to ensure that only valid data is saved into your
database. For example, it may be important to your application to ensure that
every user provides a valid email address and mailing address. Model-level
validations are the best way to ensure that only valid data is saved into your
database. They are database agnostic, cannot be bypassed by end users, and are
convenient to test and maintain. Rails makes them easy to use, provides
built-in helpers for common needs, and allows you to create your own validation
methods as well.
There are several other ways to validate data before it is saved into your
2015-05-16 12:06:34 -04:00
database, including native database constraints, client-side validations and
2012-11-29 18:24:08 -05:00
controller-level validations. Here's a summary of the pros and cons:
* Database constraints and/or stored procedures make the validation mechanisms
database-dependent and can make testing and maintenance more difficult.
However, if your database is used by other applications, it may be a good
idea to use some constraints at the database level. Additionally,
database-level validations can safely handle some things (such as uniqueness
in heavily-used tables) that can be difficult to implement otherwise.
* Client-side validations can be useful, but are generally unreliable if used
alone. If they are implemented using JavaScript, they may be bypassed if
JavaScript is turned off in the user's browser. However, if combined with
other techniques, client-side validation can be a convenient way to provide
users with immediate feedback as they use your site.
* Controller-level validations can be tempting to use, but often become
unwieldy and difficult to test and maintain. Whenever possible, it's a good
idea to keep your controllers skinny, as it will make your application a
pleasure to work with in the long run.
Choose these in certain, specific cases. It's the opinion of the Rails team
that model-level validations are the most appropriate in most circumstances.
2012-10-17 09:15:55 -04:00
### When Does Validation Happen?
2012-11-29 18:24:08 -05:00
There are two kinds of Active Record objects: those that correspond to a row
inside your database and those that do not. When you create a fresh object, for
example using the `new` method, that object does not belong to the database
yet. Once you call `save` upon that object it will be saved into the
appropriate database table. Active Record uses the `new_record?` instance
method to determine whether an object is already in the database or not.
Consider the following simple Active Record class:
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
end
```
We can see how it works by looking at some `rails console` output:
```ruby
2014-05-20 07:29:18 -04:00
$ bin/rails console
2012-10-17 09:15:55 -04:00
>> p = Person.new(name: "John Doe")
=> #< Person id: nil , name: " John Doe " , created_at: nil , updated_at: nil >
>> p.new_record?
=> true
>> p.save
=> true
>> p.new_record?
=> false
```
2012-11-29 18:24:08 -05:00
Creating and saving a new record will send an SQL `INSERT` operation to the
database. Updating an existing record will send an SQL `UPDATE` operation
instead. Validations are typically run before these commands are sent to the
database. If any validations fail, the object will be marked as invalid and
Active Record will not perform the `INSERT` or `UPDATE` operation. This avoids
storing an invalid object in the database. You can choose to have specific
validations run when an object is created, saved, or updated.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
CAUTION: There are many ways to change the state of an object in the database.
Some methods will trigger validations, but some will not. This means that it's
possible to save an object in the database in an invalid state if you aren't
careful.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
The following methods trigger validations, and will save the object to the
database only if the object is valid:
2012-10-17 09:15:55 -04:00
* `create`
* `create!`
* `save`
* `save!`
* `update`
2013-01-02 16:40:48 -05:00
* `update!`
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
The bang versions (e.g. `save!` ) raise an exception if the record is invalid.
2015-05-16 12:06:34 -04:00
The non-bang versions don't: `save` and `update` return `false` , and
2013-07-19 01:44:53 -04:00
`create` just returns the object.
2012-10-17 09:15:55 -04:00
### Skipping Validations
2012-11-29 18:24:08 -05:00
The following methods skip validations, and will save the object to the
database regardless of its validity. They should be used with caution.
2012-10-17 09:15:55 -04:00
* `decrement!`
* `decrement_counter`
* `increment!`
* `increment_counter`
* `toggle!`
* `touch`
* `update_all`
* `update_attribute`
* `update_column`
* `update_columns`
* `update_counters`
2012-11-29 18:24:08 -05:00
Note that `save` also has the ability to skip validations if passed `validate:
2015-05-16 12:06:34 -04:00
false` as an argument. This technique should be used with caution.
2012-10-17 09:15:55 -04:00
* `save(validate: false)`
### `valid?` and `invalid?`
2015-07-07 12:09:17 -04:00
Before saving an ActiveRecord object, Rails runs your validations.
If these validations produce any errors, Rails does not save the object.
You can also run these validations on your own. `valid?` triggers your validations
2012-11-29 18:24:08 -05:00
and returns true if no errors were found in the object, and false otherwise.
As you saw above:
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, presence: true
end
Person.create(name: "John Doe").valid? # => true
Person.create(name: nil).valid? # => false
```
2012-11-29 18:24:08 -05:00
After Active Record has performed validations, any errors found can be accessed
2013-05-16 13:46:00 -04:00
through the `errors.messages` instance method, which returns a collection of errors.
By definition, an object is valid if this collection is empty after running
2012-11-29 18:24:08 -05:00
validations.
2012-10-17 09:15:55 -04:00
2015-07-07 12:09:17 -04:00
Note that an object instantiated with `new` will not report errors
even if it's technically invalid, because validations are automatically run
only when the object is saved, such as with the `create` or `save` methods.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, presence: true
end
>> p = Person.new
2013-11-12 08:53:42 -05:00
# => #<Person id: nil, name: nil>
2013-05-16 13:46:00 -04:00
>> p.errors.messages
2013-11-12 08:53:42 -05:00
# => {}
2012-10-17 09:15:55 -04:00
>> p.valid?
2013-11-12 08:53:42 -05:00
# => false
2013-05-16 13:46:00 -04:00
>> p.errors.messages
2013-11-12 08:53:42 -05:00
# => {name:["can't be blank"]}
2012-10-17 09:15:55 -04:00
>> p = Person.create
2013-11-12 08:53:42 -05:00
# => #<Person id: nil, name: nil>
2013-05-16 13:46:00 -04:00
>> p.errors.messages
2013-11-12 08:53:42 -05:00
# => {name:["can't be blank"]}
2012-10-17 09:15:55 -04:00
>> p.save
2013-11-12 08:53:42 -05:00
# => false
2012-10-17 09:15:55 -04:00
>> p.save!
2013-11-12 08:53:42 -05:00
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
2012-10-17 09:15:55 -04:00
>> Person.create!
2013-11-12 08:53:42 -05:00
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
2012-10-17 09:15:55 -04:00
```
2012-11-29 18:24:08 -05:00
`invalid?` is simply the inverse of `valid?` . It triggers your validations,
returning true if any errors were found in the object, and false otherwise.
2012-10-17 09:15:55 -04:00
### `errors[]`
2012-11-29 18:24:08 -05:00
To verify whether or not a particular attribute of an object is valid, you can
use `errors[:attribute]` . It returns an array of all the errors for
`:attribute` . If there are no errors on the specified attribute, an empty array
is returned.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
This method is only useful _after_ validations have been run, because it only
inspects the errors collection and does not trigger validations itself. It's
different from the `ActiveRecord::Base#invalid?` method explained above because
it doesn't verify the validity of the object as a whole. It only checks to see
whether there are errors found on an individual attribute of the object.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, presence: true
end
>> Person.new.errors[:name].any? # => false
>> Person.create.errors[:name].any? # => true
```
2012-11-29 18:24:08 -05:00
We'll cover validation errors in greater depth in the [Working with Validation
2015-01-04 03:18:03 -05:00
Errors](#working-with-validation-errors) section.
### `errors.details`
2015-02-15 06:30:38 -05:00
To check which validations failed on an invalid attribute, you can use
`errors.details[:attribute]` . It returns an array of hashes with an `:error`
key to get the symbol of the validator:
2015-01-04 03:18:03 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2015-01-04 03:18:03 -05:00
validates :name, presence: true
end
>> person = Person.new
>> person.valid?
2015-09-19 04:14:54 -04:00
>> person.errors.details[:name] # => [{error: :blank}]
2015-01-04 03:18:03 -05:00
```
2015-02-15 06:30:38 -05:00
Using `details` with custom validators is covered in the [Working with
2015-01-04 03:18:03 -05:00
Validation Errors](#working-with-validation-errors) section.
2012-10-17 09:15:55 -04:00
Validation Helpers
------------------
2012-11-29 18:24:08 -05:00
Active Record offers many pre-defined validation helpers that you can use
directly inside your class definitions. These helpers provide common validation
rules. Every time a validation fails, an error message is added to the object's
`errors` collection, and this message is associated with the attribute being
validated.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Each helper accepts an arbitrary number of attribute names, so with a single
line of code you can add the same kind of validation to several attributes.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
All of them accept the `:on` and `:message` options, which define when the
validation should be run and what message should be added to the `errors`
collection if it fails, respectively. The `:on` option takes one of the values
2013-08-03 10:05:11 -04:00
`:create` or `:update` . There is a default error
2012-11-29 18:24:08 -05:00
message for each one of the validation helpers. These messages are used when
the `:message` option isn't specified. Let's take a look at each one of the
available helpers.
2012-10-17 09:15:55 -04:00
### `acceptance`
2012-11-29 18:24:08 -05:00
This method validates that a checkbox on the user interface was checked when a
form was submitted. This is typically used when the user needs to agree to your
2015-05-16 12:06:34 -04:00
application's terms of service, confirm that some text is read, or any similar
2015-07-16 00:53:42 -04:00
concept.
This validation is very specific to web applications and this
'acceptance' does not need to be recorded anywhere in your database. If you
don't have a field for it, the helper will just create a virtual attribute. If
the field does exist in your database, the `accept` option must be set to
`true` or else the validation will not run.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :terms_of_service, acceptance: true
end
```
2015-05-19 22:20:10 -04:00
This check is performed only if `terms_of_service` is not `nil` .
2012-12-04 16:50:27 -05:00
The default error message for this helper is _"must be accepted"_ .
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
It can receive an `:accept` option, which determines the value that will be
considered acceptance. It defaults to "1" and can be easily changed.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :terms_of_service, acceptance: { accept: 'yes' }
end
```
### `validates_associated`
2012-11-29 18:24:08 -05:00
You should use this helper when your model has associations with other models
and they also need to be validated. When you try to save your object, `valid?`
will be called upon each one of the associated objects.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Library < ApplicationRecord
2012-10-17 09:15:55 -04:00
has_many :books
validates_associated :books
end
```
This validation will work with all of the association types.
2012-11-29 18:24:08 -05:00
CAUTION: Don't use `validates_associated` on both ends of your associations.
They would call each other in an infinite loop.
2012-10-17 09:15:55 -04:00
2012-12-04 16:50:27 -05:00
The default error message for `validates_associated` is _"is invalid"_ . Note
2012-11-29 18:24:08 -05:00
that each associated object will contain its own `errors` collection; errors do
not bubble up to the calling model.
2012-10-17 09:15:55 -04:00
### `confirmation`
2012-11-29 18:24:08 -05:00
You should use this helper when you have two text fields that should receive
exactly the same content. For example, you may want to confirm an email address
or a password. This validation creates a virtual attribute whose name is the
name of the field that has to be confirmed with "_confirmation" appended.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :email, confirmation: true
end
```
In your view template you could use something like
```erb
< %= text_field :person, :email %>
< %= text_field :person, :email_confirmation %>
```
2012-11-29 18:24:08 -05:00
This check is performed only if `email_confirmation` is not `nil` . To require
confirmation, make sure to add a presence check for the confirmation attribute
2015-05-16 12:06:34 -04:00
(we'll take a look at `presence` later on in this guide):
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :email, confirmation: true
validates :email_confirmation, presence: true
end
```
2015-09-01 01:12:51 -04:00
There is also a `:case_sensitive` option that you can use to define whether the
confirmation constraint will be case sensitive or not. This option defaults to
true.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2015-09-01 01:12:51 -04:00
validates :email, confirmation: { case_sensitive: false }
end
```
2012-12-04 16:50:27 -05:00
The default error message for this helper is _"doesn't match confirmation"_ .
2012-10-17 09:15:55 -04:00
### `exclusion`
2012-11-29 18:24:08 -05:00
This helper validates that the attributes' values are not included in a given
set. In fact, this set can be any enumerable object.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Account < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :subdomain, exclusion: { in: %w(www us ca jp),
2013-12-01 01:01:28 -05:00
message: "%{value} is reserved." }
2012-10-17 09:15:55 -04:00
end
```
2012-11-29 18:24:08 -05:00
The `exclusion` helper has an option `:in` that receives the set of values that
will not be accepted for the validated attributes. The `:in` option has an
alias called `:within` that you can use for the same purpose, if you'd like to.
This example uses the `:message` option to show how you can include the
attribute's value.
2012-10-17 09:15:55 -04:00
2012-12-04 16:50:27 -05:00
The default error message is _"is reserved"_ .
2012-10-17 09:15:55 -04:00
### `format`
2012-11-29 18:24:08 -05:00
This helper validates the attributes' values by testing whether they match a
given regular expression, which is specified using the `:with` option.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Product < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
2013-06-08 12:36:53 -04:00
message: "only allows letters" }
2012-10-17 09:15:55 -04:00
end
```
2014-10-16 07:24:32 -04:00
Alternatively, you can require that the specified attribute does _not_ match the regular expression by using the `:without` option.
2012-12-04 16:50:27 -05:00
The default error message is _"is invalid"_ .
2012-10-17 09:15:55 -04:00
### `inclusion`
2012-11-29 18:24:08 -05:00
This helper validates that the attributes' values are included in a given set.
In fact, this set can be any enumerable object.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Coffee < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }
end
```
2012-11-29 18:24:08 -05:00
The `inclusion` helper has an option `:in` that receives the set of values that
will be accepted. The `:in` option has an alias called `:within` that you can
use for the same purpose, if you'd like to. The previous example uses the
`:message` option to show how you can include the attribute's value.
2012-10-17 09:15:55 -04:00
2012-12-04 16:50:27 -05:00
The default error message for this helper is _"is not included in the list"_ .
2012-10-17 09:15:55 -04:00
### `length`
2012-11-29 18:24:08 -05:00
This helper validates the length of the attributes' values. It provides a
variety of options, so you can specify length constraints in different ways:
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
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.
2012-11-29 18:24:08 -05:00
* `:in` (or `:within` ) - The attribute length must be included in a given
interval. The value for this option must be a range.
2012-10-17 09:15:55 -04:00
* `:is` - The attribute length must be equal to the given value.
2012-11-29 18:24:08 -05:00
The default error messages depend on the type of length validation being
performed. You can personalize these messages using the `:wrong_length` ,
`:too_long` , and `:too_short` options and `%{count}` as a placeholder for the
number corresponding to the length constraint being used. You can still use the
`:message` option to specify an error message.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :bio, length: { maximum: 1000,
too_long: "%{count} characters is the maximum allowed" }
end
```
2012-11-29 18:24:08 -05:00
Note that the default error messages are plural (e.g., "is too short (minimum
is %{count} characters)"). For this reason, when `:minimum` is 1 you should
2013-04-15 18:56:12 -04:00
provide a personalized message or use `presence: true` instead. When
2012-11-29 18:24:08 -05:00
`:in` or `:within` have a lower limit of 1, you should either provide a
personalized message or call `presence` prior to `length` .
2012-10-17 09:15:55 -04:00
### `numericality`
2012-11-29 18:24:08 -05:00
This helper validates that your attributes have only numeric values. By
default, it will match an optional sign followed by an integral or floating
point number. To specify that only integral numbers are allowed set
`:only_integer` to true.
2012-10-17 09:15:55 -04:00
If you set `:only_integer` to `true` , then it will use the
```ruby
2015-01-22 08:56:41 -05:00
/\A[+-]?\d+\z/
2012-10-17 09:15:55 -04:00
```
2012-11-29 18:24:08 -05:00
regular expression to validate the attribute's value. Otherwise, it will try to
convert the value to a number using `Float` .
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
WARNING. Note that the regular expression above allows a trailing newline
character.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Player < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :points, numericality: true
validates :games_played, numericality: { only_integer: true }
end
```
2012-11-29 18:24:08 -05:00
Besides `:only_integer` , this helper also accepts the following options to add
constraints to acceptable values:
* `:greater_than` - Specifies the value must be greater than the supplied
2012-12-04 16:50:27 -05:00
value. The default error message for this option is _"must be greater than
%{count}"_.
2012-11-29 18:24:08 -05:00
* `:greater_than_or_equal_to` - Specifies the value must be greater than or
equal to the supplied value. The default error message for this option is
2012-12-04 16:50:27 -05:00
_"must be greater than or equal to %{count}"_ .
2012-11-29 18:24:08 -05:00
* `:equal_to` - Specifies the value must be equal to the supplied value. The
2012-12-04 16:50:27 -05:00
default error message for this option is _"must be equal to %{count}"_ .
2012-11-29 18:24:08 -05:00
* `:less_than` - Specifies the value must be less than the supplied value. The
2012-12-04 16:50:27 -05:00
default error message for this option is _"must be less than %{count}"_ .
2015-05-16 12:06:34 -04:00
* `:less_than_or_equal_to` - Specifies the value must be less than or equal to
the supplied value. The default error message for this option is _"must be
less than or equal to %{count}"_.
2012-11-29 18:24:08 -05:00
* `:odd` - Specifies the value must be an odd number if set to true. The
2012-12-04 16:50:27 -05:00
default error message for this option is _"must be odd"_ .
2012-11-29 18:24:08 -05:00
* `:even` - Specifies the value must be an even number if set to true. The
2012-12-04 16:50:27 -05:00
default error message for this option is _"must be even"_ .
2012-10-17 09:15:55 -04:00
2014-12-09 13:51:21 -05:00
NOTE: By default, `numericality` doesn't allow `nil` values. You can use `allow_nil: true` option to permit it.
2012-12-04 16:50:27 -05:00
The default error message is _"is not a number"_ .
2012-10-17 09:15:55 -04:00
### `presence`
2012-11-29 18:24:08 -05:00
This helper validates that the specified attributes are not empty. It uses the
`blank?` method to check if the value is either `nil` or a blank string, that
is, a string that is either empty or consists of whitespace.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, :login, :email, presence: true
end
```
2012-11-29 18:24:08 -05:00
If you want to be sure that an association is present, you'll need to test
2012-12-13 14:58:49 -05:00
whether the associated object itself is present, and not the foreign key used
to map the association.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class LineItem < ApplicationRecord
2012-10-17 09:15:55 -04:00
belongs_to :order
2012-11-27 11:51:36 -05:00
validates :order, presence: true
2012-10-17 09:15:55 -04:00
end
```
2012-12-13 15:04:21 -05:00
In order to validate associated records whose presence is required, you must
2012-12-15 10:45:05 -05:00
specify the `:inverse_of` option for the association:
2012-11-27 11:56:45 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Order < ApplicationRecord
2012-11-27 11:56:45 -05:00
has_many :line_items, inverse_of: :order
2012-10-17 09:15:55 -04:00
end
```
2012-11-29 18:24:08 -05:00
If you validate the presence of an object associated via a `has_one` or
`has_many` relationship, it will check that the object is neither `blank?` nor
`marked_for_destruction?` .
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Since `false.blank?` is true, if you want to validate the presence of a boolean
2014-10-03 20:36:56 -04:00
field you should use one of the following validations:
2012-10-17 09:15:55 -04:00
2014-10-03 20:36:56 -04:00
```ruby
validates :boolean_field_name, inclusion: { in: [true, false] }
validates :boolean_field_name, exclusion: { in: [nil] }
```
2014-10-25 09:33:15 -04:00
2014-10-03 20:36:56 -04:00
By using one of these validations, you will ensure the value will NOT be `nil`
which would result in a `NULL` value in most cases.
2012-10-17 09:15:55 -04:00
2013-03-13 09:11:46 -04:00
### `absence`
This helper validates that the specified attributes are absent. It uses the
`present?` method to check if the value is not either nil or a blank string, that
is, a string that is either empty or consists of whitespace.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2013-03-13 09:11:46 -04:00
validates :name, :login, :email, absence: true
end
```
If you want to be sure that an association is absent, you'll need to test
whether the associated object itself is absent, and not the foreign key used
to map the association.
```ruby
2015-12-12 08:25:00 -05:00
class LineItem < ApplicationRecord
2013-03-13 09:11:46 -04:00
belongs_to :order
validates :order, absence: true
end
```
In order to validate associated records whose absence is required, you must
specify the `:inverse_of` option for the association:
```ruby
2015-12-12 08:25:00 -05:00
class Order < ApplicationRecord
2013-03-13 09:11:46 -04:00
has_many :line_items, inverse_of: :order
end
```
If you validate the absence of an object associated via a `has_one` or
`has_many` relationship, it will check that the object is neither `present?` nor
`marked_for_destruction?` .
2013-03-13 09:18:37 -04:00
Since `false.present?` is false, if you want to validate the absence of a boolean
field you should use `validates :field_name, exclusion: { in: [true, false] }` .
2013-03-13 09:11:46 -04:00
The default error message is _"must be blank"_ .
2012-10-17 09:15:55 -04:00
### `uniqueness`
2012-11-29 18:24:08 -05:00
This helper validates that the attribute's value is unique right before the
object gets saved. It does not create a uniqueness constraint in the database,
so it may happen that two different database connections create two records
with the same value for a column that you intend to be unique. To avoid that,
2015-02-04 11:04:07 -05:00
you must create a unique index on that column in your database.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Account < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :email, uniqueness: true
end
```
2012-11-29 18:24:08 -05:00
The validation happens by performing an SQL query into the model's table,
searching for an existing record with the same value in that attribute.
2012-10-17 09:15:55 -04:00
2015-05-03 03:11:06 -04:00
There is a `:scope` option that you can use to specify one or more attributes that
2012-11-29 18:24:08 -05:00
are used to limit the uniqueness check:
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Holiday < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, uniqueness: { scope: :year,
message: "should happen once per year" }
end
```
2015-05-20 03:23:01 -04:00
Should you wish to create a database constraint to prevent possible violations of a uniqueness validation using the `:scope` option, you must create a unique index on both columns in your database. See [the MySQL manual ](http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html ) for more details about multiple column indexes or [the PostgreSQL manual ](http://www.postgresql.org/docs/current/static/ddl-constraints.html ) for examples of unique constraints that refer to a group of columns.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
There is also a `:case_sensitive` option that you can use to define whether the
uniqueness constraint will be case sensitive or not. This option defaults to
true.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, uniqueness: { case_sensitive: false }
end
```
2012-11-29 18:24:08 -05:00
WARNING. Note that some databases are configured to perform case-insensitive
searches anyway.
2012-10-17 09:15:55 -04:00
2012-12-04 16:50:27 -05:00
The default error message is _"has already been taken"_ .
2012-10-17 09:15:55 -04:00
### `validates_with`
This helper passes the record to a separate class for validation.
```ruby
class GoodnessValidator < ActiveModel::Validator
def validate(record)
if record.first_name == "Evil"
record.errors[:base] < < "This person is evil"
end
end
end
2014-01-24 14:24:06 -05:00
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2014-01-24 14:24:06 -05:00
validates_with GoodnessValidator
end
2012-10-17 09:15:55 -04:00
```
2012-11-29 18:24:08 -05:00
NOTE: Errors added to `record.errors[:base]` relate to the state of the record
as a whole, and not to a specific attribute.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
The `validates_with` helper takes a class, or a list of classes to use for
validation. There is no default error message for `validates_with` . You must
manually add errors to the record's errors collection in the validator class.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
To implement the validate method, you must have a `record` parameter defined,
which is the record to be validated.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Like all other validations, `validates_with` takes the `:if` , `:unless` and
`:on` options. If you pass any other options, it will send those options to the
validator class as `options` :
2012-10-17 09:15:55 -04:00
```ruby
class GoodnessValidator < ActiveModel::Validator
def validate(record)
if options[:fields].any?{|field| record.send(field) == "Evil" }
record.errors[:base] < < "This person is evil"
end
end
end
2014-01-24 14:24:06 -05:00
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2014-01-24 14:24:06 -05:00
validates_with GoodnessValidator, fields: [:first_name, :last_name]
end
2012-10-17 09:15:55 -04:00
```
2013-02-09 09:47:22 -05:00
Note that the validator will be initialized *only once* for the whole application
life cycle, and not on each validation run, so be careful about using instance
variables inside it.
If your validator is complex enough that you want instance variables, you can
easily use a plain old Ruby object instead:
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2013-02-09 09:47:22 -05:00
validate do |person|
GoodnessValidator.new(person).validate
end
end
class GoodnessValidator
def initialize(person)
@person = person
end
2013-05-28 08:19:22 -04:00
2013-02-09 09:47:22 -05:00
def validate
if some_complex_condition_involving_ivars_and_private_methods?
@person .errors[:base] << "This person is evil"
end
end
2013-05-28 08:19:22 -04:00
2013-08-23 11:59:11 -04:00
# ...
2013-02-09 09:47:22 -05:00
end
```
2012-10-17 09:15:55 -04:00
### `validates_each`
2012-11-29 18:24:08 -05:00
This helper validates attributes against a block. It doesn't have a predefined
validation function. You should create one using a block, and every attribute
passed to `validates_each` will be tested against it. In the following example,
we don't want names and surnames to begin with lower case.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates_each :name, :surname do |record, attr, value|
2014-10-19 08:56:51 -04:00
record.errors.add(attr, 'must start with upper case') if value =~ /\A[[:lower:]]/
2012-10-17 09:15:55 -04:00
end
end
```
2012-11-29 18:24:08 -05:00
The block receives the record, the attribute's name and the attribute's value.
You can do anything you like to check for valid data within the block. If your
validation fails, you should add an error message to the model, therefore
making it invalid.
2012-10-17 09:15:55 -04:00
Common Validation Options
-------------------------
These are common validation options:
### `:allow_nil`
2012-11-29 18:24:08 -05:00
The `:allow_nil` option skips the validation when the value being validated is
`nil` .
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Coffee < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }, allow_nil: true
end
```
### `:allow_blank`
2012-11-29 18:24:08 -05:00
The `:allow_blank` option is similar to the `:allow_nil` option. This option
will let validation pass if the attribute's value is `blank?` , like `nil` or an
empty string for example.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Topic < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :title, length: { is: 5 }, allow_blank: true
end
2013-06-12 17:04:40 -04:00
Topic.create(title: "").valid? # => true
Topic.create(title: nil).valid? # => true
2012-10-17 09:15:55 -04:00
```
### `:message`
2012-11-29 18:24:08 -05:00
As you've already seen, the `:message` option lets you specify the message that
will be added to the `errors` collection when validation fails. When this
option is not used, Active Record will use the respective default error message
2015-11-27 09:04:36 -05:00
for each validation helper. The `:message` option accepts a `String` or `Proc` .
A `String` `:message` value can optionally contain any/all of `%{value}` ,
`%{attribute}` , and `%{model}` which will be dynamically replaced when
validation fails.
2015-11-30 04:30:01 -05:00
A `Proc` `:message` value is given two arguments: a message key for i18n, and
2015-11-27 09:04:36 -05:00
a hash with `:model` , `:attribute` , and `:value` key-value pairs.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2015-11-27 09:04:36 -05:00
# Hard-coded message
validates :name, presence: { message: "must be given please" }
# Message with dynamic attribute value. %{value} will be replaced with
# the actual value of the attribute. %{attribute} and %{model} also
# available.
validates :age, numericality: { message: "%{value} seems wrong" }
# Proc
validates :username,
uniqueness: {
# key = "activerecord.errors.models.person.attributes.username.taken"
# data = { model: "Person", attribute: "Username", value: < username > }
message: ->(key, data) do
"#{data[:value]} taken! Try again #{Time.zone.tomorrow}"
end
}
end
```
2012-10-17 09:15:55 -04:00
### `:on`
2012-11-29 18:24:08 -05:00
The `:on` option lets you specify when the validation should happen. The
default behavior for all the built-in validation helpers is to be run on save
(both when you're creating a new record and when you're updating it). If you
want to change it, you can use `on: :create` to run the validation only when a
new record is created or `on: :update` to run the validation only when a record
is updated.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
# it will be possible to update email with a duplicated value
validates :email, uniqueness: true, on: :create
# it will be possible to create the record with a non-numerical age
validates :age, numericality: true, on: :update
# the default (validates on both create and update)
2013-08-03 10:05:11 -04:00
validates :name, presence: true
2012-10-17 09:15:55 -04:00
end
```
Strict Validations
------------------
2012-11-29 18:24:08 -05:00
You can also specify validations to be strict and raise
`ActiveModel::StrictValidationFailed` when the object is invalid.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :name, presence: { strict: true }
end
2012-12-04 16:50:27 -05:00
Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
2012-10-17 09:15:55 -04:00
```
2015-05-16 12:06:34 -04:00
There is also the ability to pass a custom exception to the `:strict` option.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
end
2012-12-04 16:50:27 -05:00
Person.new.valid? # => TokenGenerationException: Token can't be blank
2012-10-17 09:15:55 -04:00
```
Conditional Validation
----------------------
2012-11-29 18:24:08 -05:00
Sometimes it will make sense to validate an object only when a given predicate
is satisfied. You can do that by using the `:if` and `:unless` options, which
can take a symbol, a string, a `Proc` or an `Array` . You may use the `:if`
option when you want to specify when the validation **should** happen. If you
want to specify when the validation **should not** happen, then you may use the
`:unless` option.
2012-10-17 09:15:55 -04:00
### Using a Symbol with `:if` and `:unless`
2012-11-29 18:24:08 -05:00
You can associate the `:if` and `:unless` options with a symbol corresponding
to the name of a method that will get called right before validation happens.
This is the most commonly used option.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Order < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
```
### Using a String with `:if` and `:unless`
2012-11-29 18:24:08 -05:00
You can also use a string that will be evaluated using `eval` and needs to
contain valid Ruby code. You should use this option only when the string
represents a really short condition.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :surname, presence: true, if: "name.nil?"
end
```
### Using a Proc with `:if` and `:unless`
2012-11-29 18:24:08 -05:00
Finally, it's possible to associate `:if` and `:unless` with a `Proc` object
which will be called. Using a `Proc` object gives you the ability to write an
inline condition instead of a separate method. This option is best suited for
one-liners.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Account < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :password, confirmation: true,
unless: Proc.new { |a| a.password.blank? }
end
```
2012-12-07 16:31:27 -05:00
### Grouping Conditional validations
2012-10-17 09:15:55 -04:00
2015-05-16 12:06:34 -04:00
Sometimes it is useful to have multiple validations use one condition. It can
2012-11-29 18:24:08 -05:00
be easily achieved using `with_options` .
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class User < ApplicationRecord
2012-10-17 09:15:55 -04:00
with_options if: :is_admin? do |admin|
admin.validates :password, length: { minimum: 10 }
admin.validates :email, presence: true
end
end
```
2015-05-16 12:06:34 -04:00
All validations inside of the `with_options` block will have automatically
passed the condition `if: :is_admin?`
2012-10-17 09:15:55 -04:00
2012-12-07 16:31:27 -05:00
### Combining Validation Conditions
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
On the other hand, when multiple conditions define whether or not a validation
should happen, an `Array` can be used. Moreover, you can apply both `:if` and
`:unless` to the same validation.
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Computer < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :mouse, presence: true,
2014-07-03 10:58:23 -04:00
if: ["market.retail?", :desktop?],
2012-10-17 09:15:55 -04:00
unless: Proc.new { |c| c.trackpad.present? }
end
```
2012-11-29 18:24:08 -05:00
The validation only runs when all the `:if` conditions and none of the
`:unless` conditions are evaluated to `true` .
2012-10-17 09:15:55 -04:00
Performing Custom Validations
-----------------------------
2012-11-29 18:24:08 -05:00
When the built-in validation helpers are not enough for your needs, you can
write your own validators or validation methods as you prefer.
2012-10-17 09:15:55 -04:00
### Custom Validators
2015-02-27 08:55:25 -05:00
Custom validators are classes that inherit from `ActiveModel::Validator` . These
classes must implement the `validate` method which takes a record as an argument
2012-11-29 18:24:08 -05:00
and performs the validation on it. The custom validator is called using the
`validates_with` method.
2012-10-17 09:15:55 -04:00
```ruby
class MyValidator < ActiveModel::Validator
def validate(record)
unless record.name.starts_with? 'X'
record.errors[:name] < < 'Need a name starting with X please!'
end
end
end
class Person
include ActiveModel::Validations
validates_with MyValidator
end
```
2012-11-29 18:24:08 -05:00
The easiest way to add custom validators for validating individual attributes
is with the convenient `ActiveModel::EachValidator` . In this case, the custom
validator class must implement a `validate_each` method which takes three
2014-07-11 09:07:34 -04:00
arguments: record, attribute, and value. These correspond to the instance, the
attribute to be validated, and the value of the attribute in the passed
2012-11-29 18:24:08 -05:00
instance.
2012-10-17 09:15:55 -04:00
```ruby
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors[attribute] < < (options[:message] || "is not an email")
end
end
end
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-10-17 09:15:55 -04:00
validates :email, presence: true, email: true
end
```
2012-11-29 18:24:08 -05:00
As shown in the example, you can also combine standard validations with your
own custom validators.
2012-10-17 09:15:55 -04:00
### Custom Methods
2012-11-29 18:24:08 -05:00
You can also create methods that verify the state of your models and add
messages to the `errors` collection when they are invalid. You must then
2015-07-07 08:39:58 -04:00
register these methods by using the `validate`
([API](http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate))
class method, passing in the symbols for the validation methods' names.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
You can pass more than one symbol for each class method and the respective
validations will be run in the same order as they were registered.
2012-10-17 09:15:55 -04:00
2015-07-07 12:09:17 -04:00
The `valid?` method will verify that the errors collection is empty,
so your custom validation methods should add errors to it when you
wish validation to fail:
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Invoice < ApplicationRecord
2012-10-17 09:15:55 -04:00
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
2012-11-25 23:46:11 -05:00
if expiration_date.present? & & expiration_date < Date.today
2012-10-17 09:15:55 -04:00
errors.add(:expiration_date, "can't be in the past")
end
end
def discount_cannot_be_greater_than_total_value
if discount > total_value
errors.add(:discount, "can't be greater than total value")
end
end
end
```
2015-07-07 12:09:17 -04:00
By default, such validations will run every time you call `valid?`
or save the object. But it is also possible to control when to run these
custom validations by giving an `:on` option to the `validate` method,
with either: `:create` or `:update` .
2012-10-17 09:15:55 -04:00
```ruby
2015-12-12 08:25:00 -05:00
class Invoice < ApplicationRecord
2012-10-17 09:15:55 -04:00
validate :active_customer, on: :create
def active_customer
errors.add(:customer_id, "is not active") unless customer.active?
end
end
```
2012-12-16 11:07:01 -05:00
Working with Validation Errors
------------------------------
In addition to the `valid?` and `invalid?` methods covered earlier, Rails provides a number of methods for working with the `errors` collection and inquiring about the validity of objects.
The following is a list of the most commonly used methods. Please refer to the `ActiveModel::Errors` documentation for a list of all the available methods.
### `errors`
Returns an instance of the class `ActiveModel::Errors` containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new
person.valid? # => false
2013-05-16 13:46:00 -04:00
person.errors.messages
2012-12-16 11:07:01 -05:00
# => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]}
person = Person.new(name: "John Doe")
person.valid? # => true
2013-05-16 13:46:00 -04:00
person.errors.messages # => {}
2012-12-16 11:07:01 -05:00
```
### `errors[]`
`errors[]` is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new(name: "John Doe")
person.valid? # => true
person.errors[:name] # => []
person = Person.new(name: "JD")
person.valid? # => false
person.errors[:name] # => ["is too short (minimum is 3 characters)"]
person = Person.new
person.valid? # => false
person.errors[:name]
# => ["can't be blank", "is too short (minimum is 3 characters)"]
```
### `errors.add`
2015-03-25 04:00:41 -04:00
The `add` method lets you add an error message related to a particular attribute. It takes as arguments the attribute and the error message.
The `errors.full_messages` method (or its equivalent, `errors.to_a` ) returns the error messages in a user-friendly format, with the capitalized attribute name prepended to each message, as shown in the examples below.
2012-12-16 11:07:01 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
def a_method_used_for_validation_purposes
errors.add(:name, "cannot contain the characters !@#%*()_-+=")
end
end
person = Person.create(name: "!@#")
person.errors[:name]
# => ["cannot contain the characters !@#%*()_-+="]
person.errors.full_messages
# => ["Name cannot contain the characters !@#%*()_-+="]
```
2015-03-25 04:00:41 -04:00
An equivalent to `errors#add` is to use `<<` to append a message to the `errors.messages` array for an attribute:
2012-12-16 11:07:01 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
def a_method_used_for_validation_purposes
2015-03-25 04:00:41 -04:00
errors.messages[:name] < < "cannot contain the characters !@#%*()_-+="
2012-12-16 11:07:01 -05:00
end
end
person = Person.create(name: "!@#")
person.errors[:name]
# => ["cannot contain the characters !@#%*()_-+="]
person.errors.to_a
# => ["Name cannot contain the characters !@#%*()_-+="]
```
2015-01-04 03:18:03 -05:00
### `errors.details`
2015-02-15 06:30:38 -05:00
You can specify a validator type to the returned error details hash using the
`errors.add` method.
2015-01-04 03:18:03 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2015-02-15 06:30:38 -05:00
def a_method_used_for_validation_purposes
errors.add(:name, :invalid_characters)
2015-01-04 03:18:03 -05:00
end
2015-02-15 06:30:38 -05:00
end
2015-01-04 03:18:03 -05:00
2015-02-15 06:30:38 -05:00
person = Person.create(name: "!@#")
2015-01-04 03:18:03 -05:00
2015-02-15 06:30:38 -05:00
person.errors.details[:name]
# => [{error: :invalid_characters}]
2015-01-04 03:18:03 -05:00
```
2015-02-15 06:30:38 -05:00
To improve the error details to contain the unallowed characters set for instance,
you can pass additional keys to `errors.add` .
2015-01-04 03:18:03 -05:00
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2015-02-15 06:30:38 -05:00
def a_method_used_for_validation_purposes
errors.add(:name, :invalid_characters, not_allowed: "!@#%*()_-+=")
2015-01-04 03:18:03 -05:00
end
2015-02-15 06:30:38 -05:00
end
2015-01-04 03:18:03 -05:00
2015-02-15 06:30:38 -05:00
person = Person.create(name: "!@#")
2015-01-04 03:18:03 -05:00
2015-02-15 06:30:38 -05:00
person.errors.details[:name]
# => [{error: :invalid_characters, not_allowed: "!@#%*()_-+="}]
2015-01-04 03:18:03 -05:00
```
2015-02-15 06:30:38 -05:00
All built in Rails validators populate the details hash with the corresponding
validator type.
2015-01-04 03:18:03 -05:00
2012-12-16 11:07:01 -05:00
### `errors[:base]`
You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can simply add a string to it and it will be used as an error message.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
def a_method_used_for_validation_purposes
errors[:base] < < "This person is invalid because ..."
end
end
```
### `errors.clear`
The `clear` method is used when you intentionally want to clear all the messages in the `errors` collection. Of course, calling `errors.clear` upon an invalid object won't actually make it valid: the `errors` collection will now be empty, but the next time you call `valid?` or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the `errors` collection will be filled again.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new
person.valid? # => false
person.errors[:name]
# => ["can't be blank", "is too short (minimum is 3 characters)"]
person.errors.clear
person.errors.empty? # => true
p.save # => false
p.errors[:name]
# => ["can't be blank", "is too short (minimum is 3 characters)"]
```
### `errors.size`
The `size` method returns the total number of error messages for the object.
```ruby
2015-12-12 08:25:00 -05:00
class Person < ApplicationRecord
2012-12-16 11:07:01 -05:00
validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new
person.valid? # => false
person.errors.size # => 2
person = Person.new(name: "Andrea", email: "andrea@example.com")
person.valid? # => true
person.errors.size # => 0
```
2012-11-29 18:24:08 -05:00
Displaying Validation Errors in Views
-------------------------------------
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Once you've created a model and added validations, if that model is created via
a web form, you probably want to display an error message when one of the
validations fail.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Because every application handles this kind of thing differently, Rails does
not include any view helpers to help you generate these messages directly.
2012-12-04 16:50:27 -05:00
However, due to the rich number of methods Rails gives you to interact with
2012-11-29 18:24:08 -05:00
validations in general, it's fairly easy to build your own. In addition, when
generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
it generates that displays the full list of errors on that model.
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
Assuming we have a model that's been saved in an instance variable named
2014-05-21 21:47:18 -04:00
`@article` , it looks like this:
2012-10-17 09:15:55 -04:00
```ruby
2014-05-21 21:47:18 -04:00
< % if @article .errors.any? %>
2012-11-29 18:24:08 -05:00
< div id = "error_explanation" >
2014-05-21 21:47:18 -04:00
< h2 > < %= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:< / h2 >
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
< ul >
2014-05-21 21:47:18 -04:00
< % @article .errors.full_messages.each do |msg| %>
2012-11-29 18:24:08 -05:00
< li > < %= msg %>< / li >
< % end %>
< / ul >
< / div >
2012-10-17 09:15:55 -04:00
< % end %>
```
2012-11-29 18:24:08 -05:00
Furthermore, if you use the Rails form helpers to generate your forms, when
a validation error occurs on a field, it will generate an extra `<div>` around
the entry.
2012-10-17 09:15:55 -04:00
```
2012-11-29 18:24:08 -05:00
< div class = "field_with_errors" >
2014-05-21 21:47:18 -04:00
< input id = "article_title" name = "article[title]" size = "30" type = "text" value = "" >
2012-11-29 18:24:08 -05:00
< / div >
2012-10-17 09:15:55 -04:00
```
2012-11-29 18:24:08 -05:00
You can then style this div however you'd like. The default scaffold that
Rails generates, for example, adds this CSS rule:
2012-10-17 09:15:55 -04:00
2012-11-29 18:24:08 -05:00
```
.field_with_errors {
padding: 2px;
background-color: red;
display: table;
}
2012-10-17 09:15:55 -04:00
```
2012-11-29 18:24:08 -05:00
This means that any field with an error ends up with a 2 pixel red border.