Document Validation
On this page
Overview
In this guide, you can learn how to define validation rules in your Mongoid models. After you implement validation into your models, Mongoid prevents you from running write operations that violate the validation rules. Use document validation to restrict data types and value ranges of document fields in your collections.
Mongoid includes ActiveModel::Validations
from Active Record to
provide validation functionality, including an associated and uniqueness
validator. To learn more, see the Active Record Validations
Rails guide and ActiveModel::Validations
Rails API documentation.
Note
Comparing Mongoid and MongoDB Validation
Validation in Mongoid applies only in the context of your application and differs from creating schema validation rules in MongoDB. This means that your validation rules do not apply to write operations that are performed outside of your application. To learn more about MongoDB schema validation, see Schema Validation in the Server manual.
Validation Helpers
Mongoid supports Active Record validation helpers that you can use when defining your model classes. You can use these helpers to set common validation rules in your application, such as checking for the presence of a field, comparing a field value to a specified value, or ensuring that a field has a unique value.
Define a Validation Rule
Use the validates
macro to create a validation rule, then include
the validation helper and the required specifications for the rule.
Tip
Each validation helper accepts one or more field names, which allows you to define the same rule for multiple fields.
The following code demonstrates how to use the presence
validation
helper to require that Person
instances contain a value for the
name
field:
class Person include Mongoid::Document field :name, type: String validates :name, presence: true end
You can learn about other useful validation helpers in the Common Validations section of this guide.
Common Validations
In this section, you can learn about the following common validation rules and view examples that use validation helpers:
Comparison Rule
You can use the comparison
helper to validate a document based on
the value of a specified field.
The comparison
helper supports the following options:
greater_than
: The value must be greater than the supplied value.greater_than_or_equal_to
: The value must be greater than or equal to the supplied value.equal_to
: The value must be equal to the supplied value.less_than
: The value must be less than the supplied value.less_than_or_equal_to
: The value must be less than or equal to the supplied value.other_than
: The value must be different than the supplied value.
This example defines the following comparison validation rules on the
Order
model:
delivery_date
: Must be after (greater than) the value oforder_date
quantity
: Must be less than5
class Order include Mongoid::Document field :order_date, type: DateTime field :delivery_date, type: DateTime field :quantity, type: Integer validates :delivery_date, comparison: { greater_than: :order_date } validates :quantity, comparison: { less_than: 5 } end
Formatting Rule
You can use the format
helper to validate a document based on
whether a field value matches a regular expression. Use the with
option to specify the regular expression.
This example defines a format validation rule on the
User
model to ensure that the username
field contains only
letters:
class User include Mongoid::Document field :username, type: String validates :username, format: { with: /\A[a-zA-Z]+\z/ } end
Tip
Alternative Helper Method
The Mongoid::Document
module provides macro methods for certain
validations. Instead of using the format
validation helper in the
validates
macro statement, you can use the
validates_format_of
method, as shown in the following code:
validates_format_of :username, with: /\A[a-zA-Z]+\z/
Inclusion or Exclusion Rule
You can use the inclusion
and exclusion
helpers to validate a
document based on whether a field value is in a specified list
of values. Use the in
option to specify the list of values.
This example defines an inclusion validation rule on the
Order
model to ensure that the shipping
field value is one of
the accepted values:
class Order include Mongoid::Document field :shipping, type: String validates :shipping, inclusion: { in: %w(standard priority overnight) } end
Presence or Absence Rule
You can use the presence
and absence
helpers to validate a
document based on whether a field value is present or absent (empty).
This example defines an absence validation rule on the
Order
model to ensure that the delivery_date
field value is
either nil
or an empty string:
class Order include Mongoid::Document field :delivery_date, type: String validates :delivery_date, absence: true end
Tip
Alternative Helper Method
The Mongoid::Document
module provides macro methods for certain
validations. Instead of using the presence
validation helper in the
validates
macro statement, you can use the
validates_presence_of
method, as shown in the following code:
validates_presence_of :delivery_date
Uniqueness Rule
You can use the uniqueness
helper to validate a
document based on whether a field value is unique from other values in
the collection. You can use the scope
option to specify one or more
field names that Mongoid uses to limit the uniqueness check.
This example defines a uniqueness validation rule on the
Person
model to ensure that the first_name
field value is
unique within documents that have the same last_name
value:
class Person include Mongoid::Document field :first_name, type: String field :last_name, type: String validates :first_name, uniqueness: { scope: :last_name } end
Tip
Alternative Helper Method
The Mongoid::Document
module provides macro methods for certain
validations. Instead of using the uniqueness
validation helper in the
validates
macro statement, you can use the
validates_uniqueness_of
method, as shown in the following code:
validates_uniqueness_of :first_name
Mongoid uses a primary
read preference when you use the
validates_uniqueness_of
method on a model, because if it
queries a secondary member of the replica set, it might read stale data.
This method takes a conditions
option that allows you to specify
conditions to add when Mongoid checks for uniqueness:
validates_uniqueness_of :name, conditions: -> { where(:age.gte => 10) }
Validate Associations
You can use the validates_associated
helper to validate any
associations that your model has. When you include this validation rule,
Mongoid validates any association documents any time you try to
save an instance. To learn more about associations, see the
Associations guide.
This example defines an association validation rule on the
Author
model to run the validation rules for the embedded Book
instances:
class Author include Mongoid::Document embeds_many :books validates_associated :books end
Important
Don't use the validates_associated
helper on both ends of your
associations because this causes Mongoid to perform validations in an
infinite loop.
Custom Validation Rules
You can use the validates_each
and validates_with
helpers to
create custom validators. To learn more about these helpers and view
examples, see the validates_each
and validates_with
references in the Active Record documentation.
To learn more about custom validators, see Performing Custom Validations in the Active Record documentation.
Behavior
Mongoid performs validation when you persist, or save, a document to the database. The following methods trigger your validation rules, so Mongoid saves the object to the database only if it passes validation:
create
save
update
When you use the !
-suffixed version of the preceding methods,
Mongoid returns an Mongoid::Errors::Validations
exception if
validation fails for an object.
Trigger Validation
You can run validations manually by using the valid?
method. This
method returns true
if the object passes validation, and
false
otherwise:
class Person include Mongoid::Document field :name, type: String field :age, type: Integer validates :age, comparison: { greater_than_or_equal_to: 0 } end # Returns true Person.new(name: "Berta Odom", age: 4).valid? # Returns false Person.new(name: "Cody Peng", age: -5).valid?
Mongoid behaves differently from Active Record when running valid?
on persisted data. Active Record's valid?
runs all
validations, but Mongoid's valid?
runs validations only on
documents that are in memory to optimize performance.
Additional Information
To learn more about the field types that you can use in Mongoid models, see the Field Types guide.
To learn more about validation methods and macros in Mongoid, see the Mongoid::Validatable module reference in the API documentation.
To view a full list of validations helpers in Active Record, see the ActiveModel::Validations::HelperMethods reference in the Rails API documentation.