validations.rb 49.9 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
module ActiveRecord
P
Pratik Naik 已提交
2
  # Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid.  Use the
3
  # +record+ method to retrieve the record which did not validate.
4 5 6 7 8
  #   begin
  #     complex_operation_that_calls_save!_internally
  #   rescue ActiveRecord::RecordInvalid => invalid
  #     puts invalid.record.errors
  #   end
9
  class RecordInvalid < ActiveRecordError
10
    attr_reader :record
11
    def initialize(record)
12
      @record = record
13
      super("Validation failed: #{@record.errors.full_messages.join(", ")}")
14
    end
15
  end
16

17
  # Active Record validation is reported to and from this object, which is used by Base#save to
18
  # determine whether the object is in a valid state to be saved. See usage example in Validations.
19
  class Errors
20
    include Enumerable
21 22 23
    
    class << self
      def default_error_messages
24 25
        ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
        I18n.translate 'activerecord.errors.messages'
26 27
      end
    end
28

29 30 31
    def initialize(base) # :nodoc:
      @base, @errors = base, {}
    end
32

33
    # Adds an error to the base object instead of any particular attribute. This is used
D
David Heinemeier Hansson 已提交
34 35
    # to report errors that don't tie to any specific attribute, but rather to the object
    # as a whole. These error messages don't get prepended with any field name when iterating
P
Pratik Naik 已提交
36
    # with +each_full+, so they should be complete sentences.
37 38 39 40
    def add_to_base(msg)
      add(:base, msg)
    end

41
    # Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
42
    # for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
43
    # error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
44 45 46 47 48
    # If no +messsage+ is supplied, :invalid is assumed.
    # If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
    def add(attribute, message = nil, options = {})
      message ||= :invalid
      message = generate_message(attribute, message, options) if message.is_a?(Symbol)
S
Sven Fuchs 已提交
49 50
      @errors[attribute.to_s] ||= []
      @errors[attribute.to_s] << message
51
    end
52

53
    # Will add an error message to each of the attributes in +attributes+ that is empty.
S
Sven Fuchs 已提交
54
    def add_on_empty(attributes, custom_message = nil)
55 56
      for attr in [attributes].flatten
        value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
57
        is_empty = value.respond_to?(:empty?) ? value.empty? : false
58
        add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
59 60
      end
    end
61

62
    # Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
S
Sven Fuchs 已提交
63
    def add_on_blank(attributes, custom_message = nil)
64 65
      for attr in [attributes].flatten
        value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
66
        add(attr, :blank, :default => custom_message) if value.blank?
67 68
      end
    end
S
Sven Fuchs 已提交
69
    
70
    # Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
71 72 73 74
    # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there, 
    # it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the 
    # default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name, 
    # translated attribute name and the value are available for interpolation.
75 76 77 78 79 80
    #
    # When using inheritence in your models, it will check all the inherited models too, but only if the model itself
    # hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
    # error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
    # 
    # <ol>
81 82 83 84
    # <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
    # <li><tt>activerecord.errors.models.admin.blank</tt></li>
    # <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
    # <li><tt>activerecord.errors.models.user.blank</tt></li>
85
    # <li><tt>activerecord.errors.messages.blank</tt></li>
86
    # <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
87 88 89
    # </ol>
    def generate_message(attribute, message = :invalid, options = {})

90 91
      message, options[:default] = options[:default], message if options[:default].is_a?(Symbol)

92
      defaults = @base.class.self_and_descendents_from_active_record.map do |klass| 
93 94
        [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{message}", 
          :"models.#{klass.name.underscore}.#{message}" ]
95 96
      end
      
97
      defaults << options.delete(:default)
98
      defaults = defaults.compact.flatten << :"messages.#{message}"
99 100

      key = defaults.shift
101
      value = @base.respond_to?(attribute) ? @base.send(attribute) : nil
102

103 104 105 106
      options = { :default => defaults,
        :model => @base.class.human_name,
        :attribute => @base.class.human_attribute_name(attribute.to_s),
        :value => value,
107
        :scope => [:activerecord, :errors]
108
      }.merge(options)
109 110

      I18n.translate(key, options)
S
Sven Fuchs 已提交
111
    end
112 113

    # Returns true if the specified +attribute+ has errors associated with it.
114 115 116 117 118 119 120 121 122
    #
    #   class Company < ActiveRecord::Base
    #     validates_presence_of :name, :address, :email
    #     validates_length_of :name, :in => 5..30
    #   end
    #
    #   company = Company.create(:address => '123 First St.')
    #   company.errors.invalid?(:name)      # => true
    #   company.errors.invalid?(:address)   # => false
123 124 125 126
    def invalid?(attribute)
      !@errors[attribute.to_s].nil?
    end

P
Pratik Naik 已提交
127
    # Returns +nil+, if no errors are associated with the specified +attribute+.
128 129 130 131 132 133 134 135 136 137 138 139
    # Returns the error message, if one error is associated with the specified +attribute+.
    # Returns an array of error messages, if more than one error is associated with the specified +attribute+.
    #
    #   class Company < ActiveRecord::Base
    #     validates_presence_of :name, :address, :email
    #     validates_length_of :name, :in => 5..30
    #   end
    #
    #   company = Company.create(:address => '123 First St.')
    #   company.errors.on(:name)      # => ["is too short (minimum is 5 characters)", "can't be blank"]
    #   company.errors.on(:email)     # => "can't be blank"
    #   company.errors.on(:address)   # => nil
140
    def on(attribute)
141 142 143
      errors = @errors[attribute.to_s]
      return nil if errors.nil?
      errors.size == 1 ? errors.first : errors
144 145 146 147
    end

    alias :[] :on

P
Pratik Naik 已提交
148
    # Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
149 150 151
    def on_base
      on(:base)
    end
152

153
    # Yields each attribute and associated message per error added.
154 155 156 157 158 159 160
    #
    #   class Company < ActiveRecord::Base
    #     validates_presence_of :name, :address, :email
    #     validates_length_of :name, :in => 5..30
    #   end
    #
    #   company = Company.create(:address => '123 First St.')
P
Pratik Naik 已提交
161 162 163 164
    #   company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
    #   # => name - is too short (minimum is 5 characters)
    #   #    name - can't be blank
    #   #    address - can't be blank
165 166 167
    def each
      @errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
    end
168

P
Pratik Naik 已提交
169
    # Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
170
    # through iteration as "First name can't be empty".
171 172 173 174 175 176 177
    #
    #   class Company < ActiveRecord::Base
    #     validates_presence_of :name, :address, :email
    #     validates_length_of :name, :in => 5..30
    #   end
    #
    #   company = Company.create(:address => '123 First St.')
P
Pratik Naik 已提交
178 179 180 181
    #   company.errors.each_full{|msg| puts msg }
    #   # => Name is too short (minimum is 5 characters)
    #   #    Name can't be blank
    #   #    Address can't be blank
182 183 184 185 186
    def each_full
      full_messages.each { |msg| yield msg }
    end

    # Returns all the full error messages in an array.
187 188 189 190 191 192 193 194 195
    #
    #   class Company < ActiveRecord::Base
    #     validates_presence_of :name, :address, :email
    #     validates_length_of :name, :in => 5..30
    #   end
    #
    #   company = Company.create(:address => '123 First St.')
    #   company.errors.full_messages # =>
    #     ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
S
Sven Fuchs 已提交
196
    def full_messages(options = {})
197
      full_messages = []
198 199

      @errors.each_key do |attr|
S
Sven Fuchs 已提交
200 201
        @errors[attr].each do |message|
          next unless message
202

203
          if attr == "base"
S
Sven Fuchs 已提交
204
            full_messages << message
205
          else
206 207 208
            #key = :"activerecord.att.#{@base.class.name.underscore.to_sym}.#{attr}" 
            attr_name = @base.class.human_attribute_name(attr)
            full_messages << attr_name + ' ' + message
209 210 211
          end
        end
      end
212
      full_messages
S
Sven Fuchs 已提交
213
    end 
214 215 216

    # Returns true if no errors have been added.
    def empty?
217
      @errors.empty?
218
    end
219 220

    # Removes all errors that have been added.
221 222 223
    def clear
      @errors = {}
    end
224

225
    # Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
226
    def size
227
      @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
228
    end
229

230 231
    alias_method :count, :size
    alias_method :length, :size
J
Jamis Buck 已提交
232

233
    # Returns an XML representation of this error object.
234 235 236 237 238 239 240
    #
    #   class Company < ActiveRecord::Base
    #     validates_presence_of :name, :address, :email
    #     validates_length_of :name, :in => 5..30
    #   end
    #
    #   company = Company.create(:address => '123 First St.')
P
Pratik Naik 已提交
241 242 243 244 245 246 247
    #   company.errors.to_xml
    #   # =>  <?xml version="1.0" encoding="UTF-8"?>
    #   #     <errors>
    #   #       <error>Name is too short (minimum is 5 characters)</error>
    #   #       <error>Name can't be blank</error>
    #   #       <error>Address can't be blank</error>
    #   #     </errors>
J
Jamis Buck 已提交
248 249 250 251 252 253 254 255 256 257
    def to_xml(options={})
      options[:root] ||= "errors"
      options[:indent] ||= 2
      options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])

      options[:builder].instruct! unless options.delete(:skip_instruct)
      options[:builder].errors do |e|
        full_messages.each { |msg| e.error(msg) }
      end
    end
258
    
259 260 261
  end


P
Pratik Naik 已提交
262 263
  # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
  #
264
  # Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
D
Initial  
David Heinemeier Hansson 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  # +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
  # that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
  #
  # Example:
  #
  #   class Person < ActiveRecord::Base
  #     protected
  #       def validate
  #         errors.add_on_empty %w( first_name last_name )
  #         errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
  #       end
  #
  #       def validate_on_create # is only run the first time a new object is saved
  #         unless valid_discount?(membership_discount)
  #           errors.add("membership_discount", "has expired")
  #         end
  #       end
  #
  #       def validate_on_update
284
  #         errors.add_to_base("No changes have occurred") if unchanged_attributes?
D
Initial  
David Heinemeier Hansson 已提交
285 286 287 288 289 290
  #       end
  #   end
  #
  #   person = Person.new("first_name" => "David", "phone_number" => "what?")
  #   person.save                         # => false (and doesn't do the save)
  #   person.errors.empty?                # => false
F
Florian Weber 已提交
291
  #   person.errors.count                 # => 2
D
Initial  
David Heinemeier Hansson 已提交
292 293
  #   person.errors.on "last_name"        # => "can't be empty"
  #   person.errors.on "phone_number"     # => "has invalid format"
294
  #   person.errors.each_full { |msg| puts msg }
295
  #                                       # => "Last name can't be empty\n" +
P
Pratik Naik 已提交
296
  #                                       #    "Phone number has invalid format"
D
Initial  
David Heinemeier Hansson 已提交
297 298 299 300
  #
  #   person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
  #   person.save # => true (and person is now saved in the database)
  #
301
  # An Errors object is automatically created for every Active Record.
D
Initial  
David Heinemeier Hansson 已提交
302
  module Validations
303
    VALIDATIONS = %w( validate validate_on_create validate_on_update )
304

305
    def self.included(base) # :nodoc:
306
      base.extend ClassMethods
D
Initial  
David Heinemeier Hansson 已提交
307
      base.class_eval do
308
        alias_method_chain :save, :validation
309
        alias_method_chain :save!, :validation
D
Initial  
David Heinemeier Hansson 已提交
310
      end
311 312

      base.send :include, ActiveSupport::Callbacks
313
      base.define_callbacks *VALIDATIONS
314 315
    end

P
Pratik Naik 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    # Active Record classes can implement validations in several ways. The highest level, easiest to read,
    # and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
    # +validates_associated+) documented below. These are sufficient for most model validations.
    #
    # Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
    # validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
    # when the record is invalid.
    #
    # At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
    # to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
    # and chaining.
    #
    # The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
    # as documented in ActiveRecord::Validations.
    #
    # == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
    #
    # Calls to these methods add a validation method or block to the class. Again, this approach is recommended
    # only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
    # insufficient to handle the required validation.
    #
    # This can be done with a symbol pointing to a method:
    #
    #   class Comment < ActiveRecord::Base
    #     validate :must_be_friends
    #
    #     def must_be_friends
    #       errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
    #     end
    #   end
    #
    # Or with a block which is passed the current record to be validated:
    #
    #   class Comment < ActiveRecord::Base
    #     validate do |comment|
    #       comment.must_be_friends
    #     end
    #
    #     def must_be_friends
    #       errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
    #     end
    #   end
    #
    # This usage applies to +validate_on_create+ and +validate_on_update+ as well.
360
    module ClassMethods
361 362 363
      DEFAULT_VALIDATION_OPTIONS = {
        :on => :save,
        :allow_nil => false,
364
        :allow_blank => false,
365 366 367 368
        :message => nil
      }.freeze

      ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
369 370 371 372
      ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
                                  :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
                                  :odd => 'odd?', :even => 'even?' }.freeze

373 374 375
      # Validates each attribute against a block.
      #
      #   class Person < ActiveRecord::Base
376 377
      #     validates_each :first_name, :last_name do |record, attr, value|
      #       record.errors.add attr, 'starts with z.' if value[0] == ?z
378 379 380 381
      #     end
      #   end
      #
      # Options:
382 383 384 385 386
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
      # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
387
      #   method, proc or string should return or evaluate to a true or false value.
388 389
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
390
      #   method, proc or string should return or evaluate to a true or false value.
391
      def validates_each(*attrs)
392
        options = attrs.extract_options!.symbolize_keys
393
        attrs   = attrs.flatten
394 395

        # Declare the validation.
396 397 398 399 400
        send(validation_method(options[:on] || :save), options) do |record|
          attrs.each do |attr|
            value = record.send(attr)
            next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
            yield record, attr, value
401 402 403 404
          end
        end
      end

405 406 407 408
      # Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
      #
      #   Model:
      #     class Person < ActiveRecord::Base
409 410
      #       validates_confirmation_of :user_name, :password
      #       validates_confirmation_of :email_address, :message => "should match confirmation"
411 412 413 414 415 416
      #     end
      #
      #   View:
      #     <%= password_field "person", "password" %>
      #     <%= password_field "person", "password_confirmation" %>
      #
417
      # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
418
      # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
419
      # only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
420 421 422
      # check for the confirmation attribute:
      #
      #   validates_presence_of :password_confirmation, :if => :password_changed?
423 424
      #
      # Configuration options:
425 426 427 428
      # * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
429
      #   method, proc or string should return or evaluate to a true or false value.
430 431
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
432
      #   method, proc or string should return or evaluate to a true or false value.
433
      def validates_confirmation_of(*attr_names)
S
Sven Fuchs 已提交
434
        configuration = { :on => :save }
435
        configuration.update(attr_names.extract_options!)
436

437
        attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
438

439
        validates_each(attr_names, configuration) do |record, attr_name, value|
S
Sven Fuchs 已提交
440
          unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
441
            record.errors.add(attr_name, :confirmation, :default => configuration[:message]) 
S
Sven Fuchs 已提交
442
          end
443 444
        end
      end
445

446 447
      # Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
      #
448 449 450 451
      #   class Person < ActiveRecord::Base
      #     validates_acceptance_of :terms_of_service
      #     validates_acceptance_of :eula, :message => "must be abided"
      #   end
452
      #
453 454
      # If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
      # performed only if +terms_of_service+ is not +nil+ and by default on save.
455
      #
456
      # Configuration options:
457 458 459 460 461 462 463 464
      # * <tt>:message</tt> - A custom error message (default is: "must be accepted").
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
      # * <tt>:accept</tt> - Specifies value that is considered accepted.  The default value is a string "1", which
      #   makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
      #   column, since the attribute is typecast from "1" to +true+ before validation.
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
465
      #   method, proc or string should return or evaluate to a true or false value.
466 467
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
468
      #   method, proc or string should return or evaluate to a true or false value.
469
      def validates_acceptance_of(*attr_names)
S
Sven Fuchs 已提交
470
        configuration = { :on => :save, :allow_nil => true, :accept => "1" }
471
        configuration.update(attr_names.extract_options!)
472

473 474
        db_cols = begin
          column_names
475
        rescue Exception # To ignore both statement and connection errors
476 477 478 479
          []
        end
        names = attr_names.reject { |name| db_cols.include?(name.to_s) }
        attr_accessor(*names)
480

481
        validates_each(attr_names,configuration) do |record, attr_name, value|
S
Sven Fuchs 已提交
482
          unless value == configuration[:accept]
483
            record.errors.add(attr_name, :accepted, :default => configuration[:message]) 
S
Sven Fuchs 已提交
484
          end
485 486
        end
      end
487

488
      # Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
489
      #
490 491 492 493 494
      #   class Person < ActiveRecord::Base
      #     validates_presence_of :first_name
      #   end
      #
      # The first_name attribute must be in the object and it cannot be blank.
495
      #
496 497 498 499
      # If you want to validate the presence of a boolean field (where the real values are true and false),
      # you will want to use validates_inclusion_of :field_name, :in => [true, false]
      # This is due to the way Object#blank? handles boolean values. false.blank? # => true
      #
500
      # Configuration options:
501 502
      # * <tt>message</tt> - A custom error message (default is: "can't be blank").
      # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
503
      # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
504 505
      #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
      #   method, proc or string should return or evaluate to a true or false value.
506
      # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
507 508
      #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
      #   method, proc or string should return or evaluate to a true or false value.
509
      #
510
      def validates_presence_of(*attr_names)
S
Sven Fuchs 已提交
511
        configuration = { :on => :save }
512
        configuration.update(attr_names.extract_options!)
513

D
David Heinemeier Hansson 已提交
514
        # can't use validates_each here, because it cannot cope with nonexistent attributes,
515
        # while errors.add_on_empty can
516 517 518
        send(validation_method(configuration[:on]), configuration) do |record|
          record.errors.add_on_blank(attr_names, configuration[:message])
        end
519
      end
520

521
      # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
522 523
      #
      #   class Person < ActiveRecord::Base
524
      #     validates_length_of :first_name, :maximum=>30
P
Pratik Naik 已提交
525
      #     validates_length_of :last_name, :maximum=>30, :message=>"less than {{count}} if you don't mind"
526
      #     validates_length_of :fax, :in => 7..32, :allow_nil => true
527
      #     validates_length_of :phone, :in => 7..32, :allow_blank => true
528
      #     validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
P
Pratik Naik 已提交
529 530 531
      #     validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least {{count}} character"
      #     validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with {{count}} characters... don't play me."
      #     validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least {{count}} words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
532 533 534
      #   end
      #
      # Configuration options:
535 536 537 538 539 540 541
      # * <tt>:minimum</tt> - The minimum size of the attribute.
      # * <tt>:maximum</tt> - The maximum size of the attribute.
      # * <tt>:is</tt> - The exact size of the attribute.
      # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
      # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
      # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
      # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
P
Pratik Naik 已提交
542 543 544
      # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is {{count}} characters)").
      # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is {{count}} characters)").
      # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be {{count}} characters)").
545 546 547 548
      # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation.  An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
549
      #   method, proc or string should return or evaluate to a true or false value.
550 551
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
552
      #   method, proc or string should return or evaluate to a true or false value.
553 554 555
      # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
      #   count words as in above example.)
      #   Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
556 557
      def validates_length_of(*attrs)
        # Merge given options with defaults.
558
        options = {
559
          :tokenizer => lambda {|value| value.split(//)}
560
        }.merge(DEFAULT_VALIDATION_OPTIONS)
561
        options.update(attrs.extract_options!.symbolize_keys)
562 563 564 565

        # Ensure that one and only one range option is specified.
        range_options = ALL_RANGE_OPTIONS & options.keys
        case range_options.size
566 567 568 569 570 571
          when 0
            raise ArgumentError, 'Range unspecified.  Specify the :within, :maximum, :minimum, or :is option.'
          when 1
            # Valid number of options; do nothing.
          else
            raise ArgumentError, 'Too many range options specified.  Choose only one.'
572
        end
573

574 575 576 577
        # Get range option and value.
        option = range_options.first
        option_value = options[range_options.first]

578
        case option
579 580 581 582
          when :within, :in
            raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)

            validates_each(attrs, options) do |record, attr, value|
583
              value = options[:tokenizer].call(value) if value.kind_of?(String)
584
              if value.nil? or value.size < option_value.begin
585
                record.errors.add(attr, :too_short, :default => options[:too_short], :count => option_value.begin)
586
              elsif value.size > option_value.end
587
                record.errors.add(attr, :too_long, :default => options[:too_long], :count => option_value.end)
588
              end
589
            end
590 591
          when :is, :minimum, :maximum
            raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
592

593 594 595
            # Declare different validations per option.
            validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
            message_options = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }
596

597
            validates_each(attrs, options) do |record, attr, value|
598
              value = options[:tokenizer].call(value) if value.kind_of?(String)
S
Sven Fuchs 已提交
599 600 601
              unless !value.nil? and value.size.method(validity_checks[option])[option_value]
                key = message_options[option]
                custom_message = options[:message] || options[key]
602
                record.errors.add(attr, key, :default => custom_message, :count => option_value) 
S
Sven Fuchs 已提交
603
              end
604
            end
605
        end
606
      end
607

608 609 610
      alias_method :validates_size_of, :validates_length_of


611 612 613
      # Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
      # can be named "davidhh".
      #
614
      #   class Person < ActiveRecord::Base
615 616 617 618
      #     validates_uniqueness_of :user_name, :scope => :account_id
      #   end
      #
      # It can also validate whether the value of the specified attributes are unique based on multiple scope parameters.  For example,
619
      # making sure that a teacher can only be on the schedule once per semester for a particular class.
620 621
      #
      #   class TeacherSchedule < ActiveRecord::Base
622
      #     validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
623
      #   end
624
      #
D
David Heinemeier Hansson 已提交
625
      # When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
626
      # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
627
      #
628
      # Because this check is performed outside the database there is still a chance that duplicate values
629
      # will be inserted in two parallel transactions.  To guarantee against this you should create a
630
      # unique index on the field. See +add_index+ for more information.
631
      #
632
      # Configuration options:
633 634
      # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
      # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
P
Pratik Naik 已提交
635
      # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
636 637 638 639
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
640
      #   method, proc or string should return or evaluate to a true or false value.
641 642
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
643
      #   method, proc or string should return or evaluate to a true or false value.
644
      def validates_uniqueness_of(*attr_names)
S
Sven Fuchs 已提交
645
        configuration = { :case_sensitive => true }
646
        configuration.update(attr_names.extract_options!)
647

648
        validates_each(attr_names,configuration) do |record, attr_name, value|
649 650 651 652 653 654 655 656 657 658 659 660 661 662
          # The check for an existing value should be run from a class that
          # isn't abstract. This means working down from the current class
          # (self), to the first non-abstract class. Since classes don't know
          # their subclasses, we have to build the hierarchy between self and
          # the record's class.
          class_hierarchy = [record.class]
          while class_hierarchy.first != self
            class_hierarchy.insert(0, class_hierarchy.first.superclass)
          end

          # Now we can work our way down the tree to the first non-abstract
          # class (which has a database table to query from).
          finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }

663 664
          is_text_column = finder_class.columns_hash[attr_name.to_s].text?

665 666
          if value.nil?
            comparison_operator = "IS ?"
667
          elsif is_text_column
668
            comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
669 670 671
            value = value.to_s
          else
            comparison_operator = "= ?"
672 673
          end

674 675
          sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"

676
          if value.nil? || (configuration[:case_sensitive] || !is_text_column)
677
            condition_sql = "#{sql_attribute} #{comparison_operator}"
678 679
            condition_params = [value]
          else
680
            condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}"
681
            condition_params = [value.mb_chars.downcase]
682
          end
683

684
          if scope = configuration[:scope]
685 686
            Array(scope).map do |scope_item|
              scope_value = record.send(scope_item)
687
              condition_sql << " AND #{record.class.quoted_table_name}.#{scope_item} #{attribute_condition(scope_value)}"
688 689
              condition_params << scope_value
            end
690
          end
691

692
          unless record.new_record?
693
            condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
694
            condition_params << record.send(:id)
695
          end
696

697 698
          finder_class.with_exclusive_scope do
            if finder_class.exists?([condition_sql, *condition_params])
699
              record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
S
Sven Fuchs 已提交
700
            end
701
          end
702 703
        end
      end
704

705

706
      # Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
707 708 709
      # provided.
      #
      #   class Person < ActiveRecord::Base
710
      #     validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
711 712
      #   end
      #
713
      # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
714
      #
715 716 717
      # A regular expression must be provided or else an exception will be raised.
      #
      # Configuration options:
718 719 720 721
      # * <tt>:message</tt> - A custom error message (default is: "is invalid").
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
      # * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
P
Pratik Naik 已提交
722
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
723 724
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
725
      #   method, proc or string should return or evaluate to a true or false value.
726 727
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
728
      #   method, proc or string should return or evaluate to a true or false value.
729
      def validates_format_of(*attr_names)
S
Sven Fuchs 已提交
730
        configuration = { :on => :save, :with => nil }
731
        configuration.update(attr_names.extract_options!)
732 733 734

        raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)

735
        validates_each(attr_names, configuration) do |record, attr_name, value|
S
Sven Fuchs 已提交
736
          unless value.to_s =~ configuration[:with]
737
            record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value) 
S
Sven Fuchs 已提交
738
          end
739 740
        end
      end
741 742 743 744

      # Validates whether the value of the specified attribute is available in a particular enumerable object.
      #
      #   class Person < ActiveRecord::Base
745 746
      #     validates_inclusion_of :gender, :in => %w( m f ), :message => "woah! what are you then!??!!"
      #     validates_inclusion_of :age, :in => 0..99
P
Pratik Naik 已提交
747
      #     validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension {{value}} is not included in the list"
748 749 750
      #   end
      #
      # Configuration options:
751 752 753 754 755 756
      # * <tt>:in</tt> - An enumerable object of available items.
      # * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
757
      #   method, proc or string should return or evaluate to a true or false value.
758 759
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
760
      #   method, proc or string should return or evaluate to a true or false value.
761
      def validates_inclusion_of(*attr_names)
762
        configuration = { :on => :save }
763
        configuration.update(attr_names.extract_options!)
764

765
        enum = configuration[:in] || configuration[:within]
766

767
        raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
768

769
        validates_each(attr_names, configuration) do |record, attr_name, value|
S
Sven Fuchs 已提交
770
          unless enum.include?(value)
771
            record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value) 
S
Sven Fuchs 已提交
772
          end
773 774
        end
      end
775

776 777 778 779 780
      # Validates that the value of the specified attribute is not in a particular enumerable object.
      #
      #   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"
P
Pratik Naik 已提交
781
      #     validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension {{value}} is not allowed"
782 783 784
      #   end
      #
      # Configuration options:
785 786 787 788 789 790
      # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
      # * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
      # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
      # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
791
      #   method, proc or string should return or evaluate to a true or false value.
792 793
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
794
      #   method, proc or string should return or evaluate to a true or false value.
795
      def validates_exclusion_of(*attr_names)
796
        configuration = { :on => :save }
797
        configuration.update(attr_names.extract_options!)
798 799 800

        enum = configuration[:in] || configuration[:within]

801
        raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
802 803

        validates_each(attr_names, configuration) do |record, attr_name, value|
S
Sven Fuchs 已提交
804
          if enum.include?(value)
805
            record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value) 
S
Sven Fuchs 已提交
806
          end
807 808 809
        end
      end

D
David Heinemeier Hansson 已提交
810
      # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
      #
      #   class Book < ActiveRecord::Base
      #     has_many :pages
      #     belongs_to :library
      #
      #     validates_associated :pages, :library
      #   end
      #
      # Warning: If, after the above definition, you then wrote:
      #
      #   class Page < ActiveRecord::Base
      #     belongs_to :book
      #
      #     validates_associated :book
      #   end
      #
827
      # this would specify a circular dependency and cause infinite recursion.
828 829
      #
      # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
830
      # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
831 832
      #
      # Configuration options:
833
      # * <tt>:message</tt> - A custom error message (default is: "is invalid")
P
Pratik Naik 已提交
834
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
835 836
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
837
      #   method, proc or string should return or evaluate to a true or false value.
838 839
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
840
      #   method, proc or string should return or evaluate to a true or false value.
841
      def validates_associated(*attr_names)
S
Sven Fuchs 已提交
842
        configuration = { :on => :save }
843
        configuration.update(attr_names.extract_options!)
844 845

        validates_each(attr_names, configuration) do |record, attr_name, value|
S
Sven Fuchs 已提交
846
          unless (value.is_a?(Array) ? value : [value]).inject(true) { |v, r| (r.nil? || r.valid?) && v }
847
            record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
S
Sven Fuchs 已提交
848
          end
849 850
        end
      end
851

852
      # Validates whether the value of the specified attribute is numeric by trying to convert it to
P
Pratik Naik 已提交
853 854
      # a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
      # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
855 856 857 858 859 860
      #
      #   class Person < ActiveRecord::Base
      #     validates_numericality_of :value, :on => :create
      #   end
      #
      # Configuration options:
861 862 863 864 865 866 867 868 869 870 871 872 873
      # * <tt>:message</tt> - A custom error message (default is: "is not a number").
      # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
      # * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
      # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
      # * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
      # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
      # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
      # * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
      # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
      # * <tt>:odd</tt> - Specifies the value must be an odd number.
      # * <tt>:even</tt> - Specifies the value must be an even number.
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
874
      #   method, proc or string should return or evaluate to a true or false value.
875 876
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
877
      #   method, proc or string should return or evaluate to a true or false value.
878
      def validates_numericality_of(*attr_names)
879
        configuration = { :on => :save, :only_integer => false, :allow_nil => false }
880 881
        configuration.update(attr_names.extract_options!)

882

883 884 885 886 887 888 889 890 891 892 893 894 895
        numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys

        (numericality_options - [ :odd, :even ]).each do |option|
          raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
        end

        validates_each(attr_names,configuration) do |record, attr_name, value|
          raw_value = record.send("#{attr_name}_before_type_cast") || value

          next if configuration[:allow_nil] and raw_value.nil?

          if configuration[:only_integer]
            unless raw_value.to_s =~ /\A[+-]?\d+\Z/
896
              record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
897 898 899 900
              next
            end
            raw_value = raw_value.to_i
          else
901
            begin
902
              raw_value = Kernel.Float(raw_value)
903
            rescue ArgumentError, TypeError
904
              record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
905 906 907 908 909 910 911
              next
            end
          end

          numericality_options.each do |option|
            case option
              when :odd, :even
S
Sven Fuchs 已提交
912
                unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
913
                  record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message]) 
S
Sven Fuchs 已提交
914
                end
915
              else
916
                record.errors.add(attr_name, option, :default => configuration[:message], :value => raw_value, :count => configuration[option]) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
917 918
            end
          end
919
        end
920
      end
921

922 923
      # Creates an object just like Base.create but calls save! instead of save
      # so an exception is raised if the record is invalid.
924
      def create!(attributes = nil, &block)
925
        if attributes.is_a?(Array)
926
          attributes.collect { |attr| create!(attr, &block) }
927 928
        else
          object = new(attributes)
929
          yield(object) if block_given?
930 931 932 933 934
          object.save!
          object
        end
      end

935 936 937 938 939 940 941 942
      private
        def validation_method(on)
          case on
            when :save   then :validate
            when :create then :validate_on_create
            when :update then :validate_on_update
          end
        end
D
Initial  
David Heinemeier Hansson 已提交
943 944 945 946 947
    end

    # The validation process on save can be skipped by passing false. The regular Base#save method is
    # replaced with this when the validations module is mixed in, which it is by default.
    def save_with_validation(perform_validation = true)
948 949 950 951 952
      if perform_validation && valid? || !perform_validation
        save_without_validation
      else
        false
      end
D
Initial  
David Heinemeier Hansson 已提交
953 954
    end

955
    # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
956
    # if the record is not valid.
957
    def save_with_validation!
958
      if valid?
959
        save_without_validation!
960 961 962
      else
        raise RecordInvalid.new(self)
      end
963 964
    end

965
    # Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
D
Initial  
David Heinemeier Hansson 已提交
966 967
    def valid?
      errors.clear
968

969
      run_callbacks(:validate)
D
Initial  
David Heinemeier Hansson 已提交
970
      validate
971

972
      if new_record?
973
        run_callbacks(:validate_on_create)
974
        validate_on_create
975
      else
976
        run_callbacks(:validate_on_update)
977 978 979
        validate_on_update
      end

D
Initial  
David Heinemeier Hansson 已提交
980 981 982 983 984
      errors.empty?
    end

    # Returns the Errors object that holds all information about attribute error messages.
    def errors
985
      @errors ||= Errors.new(self)
D
Initial  
David Heinemeier Hansson 已提交
986 987 988
    end

    protected
989
      # Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
D
Initial  
David Heinemeier Hansson 已提交
990
      def validate #:doc:
991
      end
D
Initial  
David Heinemeier Hansson 已提交
992 993 994 995 996 997 998 999 1000 1001

      # Overwrite this method for validation checks used only on creation.
      def validate_on_create #:doc:
      end

      # Overwrite this method for validation checks used only on updates.
      def validate_on_update # :doc:
      end
  end
end