Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activerecord/lib/active_record/validations.rb

Revision 9248, 47.7 kB (checked in by rick, 2 years ago)

Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. [rick]

  • Property svn:executable set to *
Line 
1 module ActiveRecord
2   # Raised by save! and create! when the record is invalid.  Use the
3   # +record+ method to retrieve the record which did not validate.
4   #   begin
5   #     complex_operation_that_calls_save!_internally
6   #   rescue ActiveRecord::RecordInvalid => invalid
7   #     puts invalid.record.errors
8   #   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     def initialize(base) # :nodoc:
23       @base, @errors = base, {}
24     end
25
26     @@default_error_messages = {
27       :inclusion => "is not included in the list",
28       :exclusion => "is reserved",
29       :invalid => "is invalid",
30       :confirmation => "doesn't match confirmation",
31       :accepted  => "must be accepted",
32       :empty => "can't be empty",
33       :blank => "can't be blank",
34       :too_long => "is too long (maximum is %d characters)",
35       :too_short => "is too short (minimum is %d characters)",
36       :wrong_length => "is the wrong length (should be %d characters)",
37       :taken => "has already been taken",
38       :not_a_number => "is not a number",
39       :greater_than => "must be greater than %d",
40       :greater_than_or_equal_to => "must be greater than or equal to %d",
41       :equal_to => "must be equal to %d",
42       :less_than => "must be less than %d",
43       :less_than_or_equal_to => "must be less than or equal to %d",
44       :odd => "must be odd",
45       :even => "must be even"
46     }
47
48     # Holds a hash with all the default error messages that can be replaced by your own copy or localizations.
49     cattr_accessor :default_error_messages
50
51
52     # Adds an error to the base object instead of any particular attribute. This is used
53     # to report errors that don't tie to any specific attribute, but rather to the object
54     # as a whole. These error messages don't get prepended with any field name when iterating
55     # with each_full, so they should be complete sentences.
56     def add_to_base(msg)
57       add(:base, msg)
58     end
59
60     # Adds an error message (+msg+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
61     # for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
62     # error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
63     # If no +msg+ is supplied, "invalid" is assumed.
64     def add(attribute, msg = @@default_error_messages[:invalid])
65       @errors[attribute.to_s] = [] if @errors[attribute.to_s].nil?
66       @errors[attribute.to_s] << msg
67     end
68
69     # Will add an error message to each of the attributes in +attributes+ that is empty.
70     def add_on_empty(attributes, msg = @@default_error_messages[:empty])
71       for attr in [attributes].flatten
72         value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
73         is_empty = value.respond_to?("empty?") ? value.empty? : false
74         add(attr, msg) unless !value.nil? && !is_empty
75       end
76     end
77
78     # Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
79     def add_on_blank(attributes, msg = @@default_error_messages[:blank])
80       for attr in [attributes].flatten
81         value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
82         add(attr, msg) if value.blank?
83       end
84     end
85
86     # Returns true if the specified +attribute+ has errors associated with it.
87     #
88     #   class Company < ActiveRecord::Base
89     #     validates_presence_of :name, :address, :email
90     #     validates_length_of :name, :in => 5..30
91     #   end
92     #
93     #   company = Company.create(:address => '123 First St.')
94     #   company.errors.invalid?(:name)      # => true
95     #   company.errors.invalid?(:address)   # => false
96     def invalid?(attribute)
97       !@errors[attribute.to_s].nil?
98     end
99
100     # Returns nil, if no errors are associated with the specified +attribute+.
101     # Returns the error message, if one error is associated with the specified +attribute+.
102     # Returns an array of error messages, if more than one error is associated with the specified +attribute+.
103     #
104     #   class Company < ActiveRecord::Base
105     #     validates_presence_of :name, :address, :email
106     #     validates_length_of :name, :in => 5..30
107     #   end
108     #
109     #   company = Company.create(:address => '123 First St.')
110     #   company.errors.on(:name)      # => ["is too short (minimum is 5 characters)", "can't be blank"]
111     #   company.errors.on(:email)     # => "can't be blank"
112     #   company.errors.on(:address)   # => nil
113     def on(attribute)
114       errors = @errors[attribute.to_s]
115       return nil if errors.nil?
116       errors.size == 1 ? errors.first : errors
117     end
118
119     alias :[] :on
120
121     # Returns errors assigned to the base object through add_to_base according to the normal rules of on(attribute).
122     def on_base
123       on(:base)
124     end
125
126     # Yields each attribute and associated message per error added.
127     #
128     #   class Company < ActiveRecord::Base
129     #     validates_presence_of :name, :address, :email
130     #     validates_length_of :name, :in => 5..30
131     #   end
132     #
133     #   company = Company.create(:address => '123 First St.')
134     #   company.errors.each{|attr,msg| puts "#{attr} - #{msg}" } # =>
135     #     name - is too short (minimum is 5 characters)
136     #     name - can't be blank
137     #     address - can't be blank
138     def each
139       @errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
140     end
141
142     # Yields each full error message added. So Person.errors.add("first_name", "can't be empty") will be returned
143     # through iteration as "First name can't be empty".
144     #
145     #   class Company < ActiveRecord::Base
146     #     validates_presence_of :name, :address, :email
147     #     validates_length_of :name, :in => 5..30
148     #   end
149     #
150     #   company = Company.create(:address => '123 First St.')
151     #   company.errors.each_full{|msg| puts msg } # =>
152     #     Name is too short (minimum is 5 characters)
153     #     Name can't be blank
154     #     Address can't be blank
155     def each_full
156       full_messages.each { |msg| yield msg }
157     end
158
159     # Returns all the full error messages in an array.
160     #
161     #   class Company < ActiveRecord::Base
162     #     validates_presence_of :name, :address, :email
163     #     validates_length_of :name, :in => 5..30
164     #   end
165     #
166     #   company = Company.create(:address => '123 First St.')
167     #   company.errors.full_messages # =>
168     #     ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
169     def full_messages
170       full_messages = []
171
172       @errors.each_key do |attr|
173         @errors[attr].each do |msg|
174           next if msg.nil?
175
176           if attr == "base"
177             full_messages << msg
178           else
179             full_messages << @base.class.human_attribute_name(attr) + " " + msg
180           end
181         end
182       end
183       full_messages
184     end
185
186     # Returns true if no errors have been added.
187     def empty?
188       @errors.empty?
189     end
190
191     # Removes all errors that have been added.
192     def clear
193       @errors = {}
194     end
195
196     # Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
197     def size
198       @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
199     end
200
201     alias_method :count, :size
202     alias_method :length, :size
203
204     # Return an XML representation of this error object.
205     #
206     #   class Company < ActiveRecord::Base
207     #     validates_presence_of :name, :address, :email
208     #     validates_length_of :name, :in => 5..30
209     #   end
210     #
211     #   company = Company.create(:address => '123 First St.')
212     #   company.errors.to_xml # =>
213     #     <?xml version="1.0" encoding="UTF-8"?>
214     #     <errors>
215     #       <error>Name is too short (minimum is 5 characters)</error>
216     #       <error>Name can't be blank</error>
217     #       <error>Address can't be blank</error>
218     #     </errors>
219     def to_xml(options={})
220       options[:root] ||= "errors"
221       options[:indent] ||= 2
222       options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
223
224       options[:builder].instruct! unless options.delete(:skip_instruct)
225       options[:builder].errors do |e|
226         full_messages.each { |msg| e.error(msg) }
227       end
228     end
229   end
230
231
232   # Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
233   # +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
234   # that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
235   #
236   # Example:
237   #
238   #   class Person < ActiveRecord::Base
239   #     protected
240   #       def validate
241   #         errors.add_on_empty %w( first_name last_name )
242   #         errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
243   #       end
244   #
245   #       def validate_on_create # is only run the first time a new object is saved
246   #         unless valid_discount?(membership_discount)
247   #           errors.add("membership_discount", "has expired")
248   #         end
249   #       end
250   #
251   #       def validate_on_update
252   #         errors.add_to_base("No changes have occurred") if unchanged_attributes?
253   #       end
254   #   end
255   #
256   #   person = Person.new("first_name" => "David", "phone_number" => "what?")
257   #   person.save                         # => false (and doesn't do the save)
258   #   person.errors.empty?                # => false
259   #   person.errors.count                 # => 2
260   #   person.errors.on "last_name"        # => "can't be empty"
261   #   person.errors.on "phone_number"     # => "has invalid format"
262   #   person.errors.each_full { |msg| puts msg }
263   #                                       # => "Last name can't be empty\n" +
264   #                                            "Phone number has invalid format"
265   #
266   #   person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
267   #   person.save # => true (and person is now saved in the database)
268   #
269   # An +Errors+ object is automatically created for every Active Record.
270   #
271   # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
272   module Validations
273     VALIDATIONS = %w( validate validate_on_create validate_on_update )
274
275     def self.included(base) # :nodoc:
276       base.extend ClassMethods
277       base.class_eval do
278         alias_method_chain :save, :validation
279         alias_method_chain :save!, :validation
280         alias_method_chain :update_attribute, :validation_skipping
281       end
282
283       base.send :include, ActiveSupport::Callbacks
284
285       VALIDATIONS.each do |validation_method|
286         base.class_eval <<-"end_eval"
287           def self.#{validation_method}(*methods, &block)
288             methods = CallbackChain.build(:#{validation_method}, *methods, &block)
289             self.#{validation_method}_callback_chain.replace(#{validation_method}_callback_chain | methods)
290           end
291
292           def self.#{validation_method}_callback_chain
293             if chain = read_inheritable_attribute(:#{validation_method})
294               return chain
295             else
296               write_inheritable_attribute(:#{validation_method}, CallbackChain.new)
297               return #{validation_method}_callback_chain
298             end
299           end
300         end_eval
301       end
302     end
303
304     # All of the following validations are defined in the class scope of the model that you're interested in validating.
305     # They offer a more declarative way of specifying when the model is valid and when it is not. It is recommended to use
306     # these over the low-level calls to validate and validate_on_create when possible.
307     module ClassMethods
308       DEFAULT_VALIDATION_OPTIONS = {
309         :on => :save,
310         :allow_nil => false,
311         :allow_blank => false,
312         :message => nil
313       }.freeze
314
315       ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
316       ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
317                                   :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
318                                   :odd => 'odd?', :even => 'even?' }.freeze
319
320       # Adds a validation method or block to the class. This is useful when
321       # overriding the #validate instance method becomes too unwieldly and
322       # you're looking for more descriptive declaration of your validations.
323       #
324       # This can be done with a symbol pointing to a method:
325       #
326       #   class Comment < ActiveRecord::Base
327       #     validate :must_be_friends
328       #
329       #     def must_be_friends
330       #       errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
331       #     end
332       #   end
333       #
334       # Or with a block which is passed the current record to be validated:
335       #
336       #   class Comment < ActiveRecord::Base
337       #     validate do |comment|
338       #       comment.must_be_friends
339       #     end
340       #
341       #     def must_be_friends
342       #       errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
343       #     end
344       #   end
345       #
346       # This usage applies to #validate_on_create and #validate_on_update as well.
347
348       # Validates each attribute against a block.
349       #
350       #   class Person < ActiveRecord::Base
351       #     validates_each :first_name, :last_name do |record, attr, value|
352       #       record.errors.add attr, 'starts with z.' if value[0] == ?z
353       #     end
354       #   end
355       #
356       # Options:
357       # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
358       # * <tt>allow_nil</tt> - Skip validation if attribute is nil.
359       # * <tt>allow_blank</tt> - Skip validation if attribute is blank.
360       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
361       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
362       #   method, proc or string should return or evaluate to a true or false value.
363       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
364       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
365       #   method, proc or string should return or evaluate to a true or false value.
366       def validates_each(*attrs)
367         options = attrs.extract_options!.symbolize_keys
368         attrs   = attrs.flatten
369
370         # Declare the validation.
371         send(validation_method(options[:on] || :save), options) do |record|
372           attrs.each do |attr|
373             value = record.send(attr)
374             next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
375             yield record, attr, value
376           end
377         end
378       end
379
380       # Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
381       #
382       #   Model:
383       #     class Person < ActiveRecord::Base
384       #       validates_confirmation_of :user_name, :password
385       #       validates_confirmation_of :email_address, :message => "should match confirmation"
386       #     end
387       #
388       #   View:
389       #     <%= password_field "person", "password" %>
390       #     <%= password_field "person", "password_confirmation" %>
391       #
392       # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
393       # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
394       # only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
395       # check for the confirmation attribute:
396       #
397       #   validates_presence_of :password_confirmation, :if => :password_changed?
398       #
399       # Configuration options:
400       # * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
401       # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
402       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
403       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
404       #   method, proc or string should return or evaluate to a true or false value.
405       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
406       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
407       #   method, proc or string should return or evaluate to a true or false value.     
408       def validates_confirmation_of(*attr_names)
409         configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
410         configuration.update(attr_names.extract_options!)
411
412         attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
413
414         validates_each(attr_names, configuration) do |record, attr_name, value|
415           record.errors.add(attr_name, configuration[:message]) unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
416         end
417       end
418
419       # Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
420       #
421       #   class Person < ActiveRecord::Base
422       #     validates_acceptance_of :terms_of_service
423       #     validates_acceptance_of :eula, :message => "must be abided"
424       #   end
425       #
426       # If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is
427       # performed only if terms_of_service is not nil and by default on save.
428       #
429       # Configuration options:
430       # * <tt>message</tt> - A custom error message (default is: "must be accepted")
431       # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
432       # * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true)
433       # * <tt>accept</tt> - Specifies value that is considered accepted.  The default value is a string "1", which
434       #   makes it easy to relate to an HTML checkbox. This should be set to 'true' if you are validating a database
435       #   column, since the attribute is typecast from "1" to <tt>true</tt> before validation.
436       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
437       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
438       #   method, proc or string should return or evaluate to a true or false value.
439       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
440       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
441       #   method, proc or string should return or evaluate to a true or false value.     
442       def validates_acceptance_of(*attr_names)
443         configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" }
444         configuration.update(attr_names.extract_options!)
445
446         db_cols = begin
447           column_names
448         rescue ActiveRecord::StatementInvalid
449           []
450         end
451         names = attr_names.reject { |name| db_cols.include?(name.to_s) }
452         attr_accessor(*names)
453
454         validates_each(attr_names,configuration) do |record, attr_name, value|
455           record.errors.add(attr_name, configuration[:message]) unless value == configuration[:accept]
456         end
457       end
458
459       # Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
460       #
461       #   class Person < ActiveRecord::Base
462       #     validates_presence_of :first_name
463       #   end
464       #
465       # The first_name attribute must be in the object and it cannot be blank.
466       #
467       # If you want to validate the presence of a boolean field (where the real values are true and false),
468       # you will want to use validates_inclusion_of :field_name, :in => [true, false]
469       # This is due to the way Object#blank? handles boolean values. false.blank? # => true
470       #
471       # Configuration options:
472       # * <tt>message</tt> - A custom error message (default is: "can't be blank")
473       # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
474       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
475       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
476       #   method, proc or string should return or evaluate to a true or false value.
477       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
478       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
479       #   method, proc or string should return or evaluate to a true or false value.
480       #
481       def validates_presence_of(*attr_names)
482         configuration = { :message => ActiveRecord::Errors.default_error_messages[:blank], :on => :save }
483         configuration.update(attr_names.extract_options!)
484
485         # can't use validates_each here, because it cannot cope with nonexistent attributes,
486         # while errors.add_on_empty can
487         send(validation_method(configuration[:on]), configuration) do |record|
488           record.errors.add_on_blank(attr_names, configuration[:message])
489         end
490       end
491
492       # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
493       #
494       #   class Person < ActiveRecord::Base
495       #     validates_length_of :first_name, :maximum=>30
496       #     validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
497       #     validates_length_of :fax, :in => 7..32, :allow_nil => true
498       #     validates_length_of :phone, :in => 7..32, :allow_blank => true
499       #     validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
500       #     validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
501       #     validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
502       #   end
503       #
504       # Configuration options:
505       # * <tt>minimum</tt> - The minimum size of the attribute
506       # * <tt>maximum</tt> - The maximum size of the attribute
507       # * <tt>is</tt> - The exact size of the attribute
508       # * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
509       # * <tt>in</tt> - A synonym(or alias) for :within
510       # * <tt>allow_nil</tt> - Attribute may be nil; skip validation.
511       # * <tt>allow_blank</tt> - Attribute may be blank; skip validation.
512       #
513       # * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
514       # * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
515       # * <tt>wrong_length</tt> - The error message if using the :is method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
516       # * <tt>message</tt> - The error message to use for a :minimum, :maximum, or :is violation.  An alias of the appropriate too_long/too_short/wrong_length message
517       # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
518       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
519       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
520       #   method, proc or string should return or evaluate to a true or false value.
521       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
522       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
523       #   method, proc or string should return or evaluate to a true or false value.     
524       def validates_length_of(*attrs)
525         # Merge given options with defaults.
526         options = {
527           :too_long     => ActiveRecord::Errors.default_error_messages[:too_long],
528           :too_short    => ActiveRecord::Errors.default_error_messages[:too_short],
529           :wrong_length => ActiveRecord::Errors.default_error_messages[:wrong_length]
530         }.merge(DEFAULT_VALIDATION_OPTIONS)
531         options.update(attrs.extract_options!.symbolize_keys)
532
533         # Ensure that one and only one range option is specified.
534         range_options = ALL_RANGE_OPTIONS & options.keys
535         case range_options.size
536           when 0
537             raise ArgumentError, 'Range unspecified.  Specify the :within, :maximum, :minimum, or :is option.'
538           when 1
539             # Valid number of options; do nothing.
540           else
541             raise ArgumentError, 'Too many range options specified.  Choose only one.'
542         end
543
544         # Get range option and value.
545         option = range_options.first
546         option_value = options[range_options.first]
547
548         case option
549           when :within, :in
550             raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
551
552             too_short = options[:too_short] % option_value.begin
553             too_long  = options[:too_long]  % option_value.end
554
555             validates_each(attrs, options) do |record, attr, value|
556               value = value.split(//) if value.kind_of?(String)
557               if value.nil? or value.size < option_value.begin
558                 record.errors.add(attr, too_short)
559               elsif value.size > option_value.end
560                 record.errors.add(attr, too_long)
561               end
562             end
563           when :is, :minimum, :maximum
564             raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
565
566             # Declare different validations per option.
567             validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
568             message_options = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }
569
570             message = (options[:message] || options[message_options[option]]) % option_value
571
572             validates_each(attrs, options) do |record, attr, value|
573               value = value.split(//) if value.kind_of?(String)
574               record.errors.add(attr, message) unless !value.nil? and value.size.method(validity_checks[option])[option_value]
575             end
576         end
577       end
578
579       alias_method :validates_size_of, :validates_length_of
580
581
582       # Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
583       # can be named "davidhh".
584       #
585       #   class Person < ActiveRecord::Base
586       #     validates_uniqueness_of :user_name, :scope => :account_id
587       #   end
588       #
589       # It can also validate whether the value of the specified attributes are unique based on multiple scope parameters.  For example,
590       # making sure that a teacher can only be on the schedule once per semester for a particular class.
591       #
592       #   class TeacherSchedule < ActiveRecord::Base
593       #     validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
594       #   end
595       #
596       # 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
597       # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
598       #
599       # Because this check is performed outside the database there is still a chance that duplicate values
600       # will be inserted in two parallel transactions.  To guarantee against this you should create a
601       # unique index on the field. See +add_index+ for more information.
602       #
603       # Configuration options:
604       # * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
605       # * <tt>scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
606       # * <tt>case_sensitive</tt> - Looks for an exact match.  Ignored by non-text columns (true by default).
607       # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
608       # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
609       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
610       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
611       #   method, proc or string should return or evaluate to a true or false value.
612       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
613       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
614       #   method, proc or string should return or evaluate to a true or false value.
615       def validates_uniqueness_of(*attr_names)
616         configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken], :case_sensitive => true }
617         configuration.update(attr_names.extract_options!)
618
619         validates_each(attr_names,configuration) do |record, attr_name, value|
620           # The check for an existing value should be run from a class that
621           # isn't abstract. This means working down from the current class
622           # (self), to the first non-abstract class. Since classes don't know
623           # their subclasses, we have to build the hierarchy between self and
624           # the record's class.
625           class_hierarchy = [record.class]
626           while class_hierarchy.first != self
627             class_hierarchy.insert(0, class_hierarchy.first.superclass)
628           end
629
630           # Now we can work our way down the tree to the first non-abstract
631           # class (which has a database table to query from).
632           finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
633
634           if value.nil? || (configuration[:case_sensitive] || !finder_class.columns_hash[attr_name.to_s].text?)
635             condition_sql = "#{record.class.quoted_table_name}.#{attr_name} #{attribute_condition(value)}"
636             condition_params = [value]
637           else
638             # sqlite has case sensitive SELECT query, while MySQL/Postgresql don't.
639             # Hence, this is needed only for sqlite.
640             condition_sql = "LOWER(#{record.class.quoted_table_name}.#{attr_name}) #{attribute_condition(value)}"
641             condition_params = [value.downcase]
642           end
643
644           if scope = configuration[:scope]
645             Array(scope).map do |scope_item|
646               scope_value = record.send(scope_item)
647               condition_sql << " AND #{record.class.quoted_table_name}.#{scope_item} #{attribute_condition(scope_value)}"
648               condition_params << scope_value
649             end
650           end
651
652           unless record.new_record?
653             condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
654             condition_params << record.send(:id)
655           end
656
657           results = finder_class.with_exclusive_scope do
658             connection.select_all(
659               construct_finder_sql(
660                 :select     => "#{attr_name}",
661                 :from       => "#{finder_class.quoted_table_name}",
662                 :conditions => [condition_sql, *condition_params]
663               )
664             )
665           end
666
667           unless results.length.zero?
668             found = true
669
670             # As MySQL/Postgres don't have case sensitive SELECT queries, we try to find duplicate
671             # column in ruby when case sensitive option
672             if configuration[:case_sensitive] && finder_class.columns_hash[attr_name.to_s].text?
673               found = results.any? { |a| a[attr_name.to_s] == value }
674             end
675
676             record.errors.add(attr_name, configuration[:message]) if found
677           end
678         end
679       end
680
681
682       # Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
683       # provided.
684       #
685       #   class Person < ActiveRecord::Base
686       #     validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
687       #   end
688       #
689       # Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
690       #
691       # A regular expression must be provided or else an exception will be raised.
692       #
693       # Configuration options:
694       # * <tt>message</tt> - A custom error message (default is: "is invalid")
695       # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
696       # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
697       # * <tt>with</tt> - The regular expression used to validate the format with (note: must be supplied!)
698       # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
699       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
700       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
701       #   method, proc or string should return or evaluate to a true or false value.
702       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
703       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
704       #   method, proc or string should return or evaluate to a true or false value.
705       def validates_format_of(*attr_names)
706         configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
707         configuration.update(attr_names.extract_options!)
708
709         raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
710
711         validates_each(attr_names, configuration) do |record, attr_name, value|
712           record.errors.add(attr_name, configuration[:message]) unless value.to_s =~ configuration[:with]
713         end
714       end
715
716       # Validates whether the value of the specified attribute is available in a particular enumerable object.
717       #
718       #   class Person < ActiveRecord::Base
719       #     validates_inclusion_of :gender, :in => %w( m f ), :message => "woah! what are you then!??!!"
720       #     validates_inclusion_of :age, :in => 0..99
721       #     validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %s is not included in the list"
722       #   end
723       #
724       # Configuration options:
725       # * <tt>in</tt> - An enumerable object of available items
726       # * <tt>message</tt> - Specifies a custom error message (default is: "is not included in the list")
727       # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
728       # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
729       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
730       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
731       #   method, proc or string should return or evaluate to a true or false value.
732       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
733       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
734       #   method, proc or string should return or evaluate to a true or false value.
735       def validates_inclusion_of(*attr_names)
736         configuration = { :message => ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }
737         configuration.update(attr_names.extract_options!)
738
739         enum = configuration[:in] || configuration[:within]
740
741         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?")
742
743         validates_each(attr_names, configuration) do |record, attr_name, value|
744           record.errors.add(attr_name, configuration[:message] % value) unless enum.include?(value)
745         end
746       end
747
748       # Validates that the value of the specified attribute is not in a particular enumerable object.
749       #
750       #   class Person < ActiveRecord::Base
751       #     validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
752       #     validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
753       #     validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %s is not allowed"
754       #   end
755       #
756       # Configuration options:
757       # * <tt>in</tt> - An enumerable object of items that the value shouldn't be part of
758       # * <tt>message</tt> - Specifies a custom error message (default is: "is reserved")
759       # * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
760       # * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
761       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
762       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
763       #   method, proc or string should return or evaluate to a true or false value.
764       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
765       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
766       #   method, proc or string should return or evaluate to a true or false value.
767       def validates_exclusion_of(*attr_names)
768         configuration = { :message => ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }
769         configuration.update(attr_names.extract_options!)
770
771         enum = configuration[:in] || configuration[:within]
772
773         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?")
774
775         validates_each(attr_names, configuration) do |record, attr_name, value|
776           record.errors.add(attr_name, configuration[:message] % value) if enum.include?(value)
777         end
778       end
779
780       # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
781       #
782       #   class Book < ActiveRecord::Base
783       #     has_many :pages
784       #     belongs_to :library
785       #
786       #     validates_associated :pages, :library
787       #   end
788       #
789       # Warning: If, after the above definition, you then wrote:
790       #
791       #   class Page < ActiveRecord::Base
792       #     belongs_to :book
793       #
794       #     validates_associated :book
795       #   end
796       #
797       # ...this would specify a circular dependency and cause infinite recursion.
798       #
799       # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
800       # is both present and guaranteed to be valid, you also need to use validates_presence_of.
801       #
802       # Configuration options:
803       # * <tt>message</tt> - A custom error message (default is: "is invalid")
804       # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
805       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
806       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
807       #   method, proc or string should return or evaluate to a true or false value.
808       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
809       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
810       #   method, proc or string should return or evaluate to a true or false value.
811       def validates_associated(*attr_names)
812         configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }
813         configuration.update(attr_names.extract_options!)
814
815         validates_each(attr_names, configuration) do |record, attr_name, value|
816           record.errors.add(attr_name, configuration[:message]) unless
817             (value.is_a?(Array) ? value : [value]).inject(true) { |v, r| (r.nil? || r.valid?) && v }
818         end
819       end
820
821       # Validates whether the value of the specified attribute is numeric by trying to convert it to
822       # a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
823       # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>integer</tt> is set to true).
824       #
825       #   class Person < ActiveRecord::Base
826       #     validates_numericality_of :value, :on => :create
827       #   end
828       #
829       # Configuration options:
830       # * <tt>message</tt> - A custom error message (default is: "is not a number")
831       # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
832       # * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
833       # * <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
834       # * <tt>greater_than</tt> Specifies the value must be greater than the supplied value
835       # * <tt>greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
836       # * <tt>equal_to</tt> Specifies the value must be equal to the supplied value
837       # * <tt>less_than</tt> Specifies the value must be less than the supplied value
838       # * <tt>less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
839       # * <tt>odd</tt> Specifies the value must be an odd number
840       # * <tt>even</tt> Specifies the value must be an even number
841       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
842       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
843       #   method, proc or string should return or evaluate to a true or false value.
844       # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
845       #   not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }).  The
846       #   method, proc or string should return or evaluate to a true or false value.
847       def validates_numericality_of(*attr_names)
848         configuration = { :on => :save, :only_integer => false, :allow_nil => false }
849         configuration.update(attr_names.extract_options!)
850
851
852         numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
853
854         (numericality_options - [ :odd, :even ]).each do |option|
855           raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
856         end
857
858         validates_each(attr_names,configuration) do |record, attr_name, value|
859           raw_value = record.send("#{attr_name}_before_type_cast") || value
860
861           next if configuration[:allow_nil] and raw_value.nil?
862
863           if configuration[:only_integer]
864             unless raw_value.to_s =~ /\A[+-]?\d+\Z/
865               record.errors.add(attr_name, configuration[:message] || ActiveRecord::Errors.default_error_messages[:not_a_number])
866               next
867             end
868             raw_value = raw_value.to_i
869           else
870            begin
871               raw_value = Kernel.Float(raw_value.to_s)
872             rescue ArgumentError, TypeError
873               record.errors.add(attr_name, configuration[:message] || ActiveRecord::Errors.default_error_messages[:not_a_number])
874               next
875             end
876           end
877
878           numericality_options.each do |option|
879             case option
880               when :odd, :even
881                 record.errors.add(attr_name, configuration[:message] || ActiveRecord::Errors.default_error_messages[option]) unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
882               else
883                 message = configuration[:message] || ActiveRecord::Errors.default_error_messages[option]
884                 message = message % configuration[option] if configuration[option]
885                 record.errors.add(attr_name, message) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
886             end
887           end
888         end
889       end
890
891       # Creates an object just like Base.create but calls save! instead of save
892       # so an exception is raised if the record is invalid.
893       def create!(attributes = nil)
894         if attributes.is_a?(Array)
895           attributes.collect { |attr| create!(attr) }
896         else
897           object = new(attributes)
898           object.save!
899           object
900         end
901       end
902
903       private
904         def validation_method(on)
905           case on
906             when :save   then :validate
907             when :create then :validate_on_create
908             when :update then :validate_on_update
909           end
910         end
911     end
912
913     # The validation process on save can be skipped by passing false. The regular Base#save method is
914     # replaced with this when the validations module is mixed in, which it is by default.
915     def save_with_validation(perform_validation = true)
916       if perform_validation && valid? || !perform_validation
917         save_without_validation
918       else
919         false
920       end
921     end
922
923     # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
924     # if the record is not valid.
925     def save_with_validation!
926       if valid?
927         save_without_validation!
928       else
929         raise RecordInvalid.new(self)
930       end
931     end
932
933     # Updates a single attribute and saves the record without going through the normal validation procedure.
934     # This is especially useful for boolean flags on existing records. The regular +update_attribute+ method
935     # in Base is replaced with this when the validations module is mixed in, which it is by default.
936     def update_attribute_with_validation_skipping(name, value)
937       send(name.to_s + '=', value)
938       save(false)
939     end
940
941     # Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false.
942     def valid?
943       errors.clear
944
945       run_callbacks(:validate)
946       validate
947
948       if new_record?
949         run_callbacks(:validate_on_create)
950         validate_on_create
951       else
952         run_callbacks(:validate_on_update)
953         validate_on_update
954       end
955
956       errors.empty?
957     end
958
959     # Returns the Errors object that holds all information about attribute error messages.
960     def errors
961       @errors ||= Errors.new(self)
962     end
963
964     protected
965       # Overwrite this method for validation checks on all saves and use Errors.add(field, msg) for invalid attributes.
966       def validate #:doc:
967       end
968
969       # Overwrite this method for validation checks used only on creation.
970       def validate_on_create #:doc:
971       end
972
973       # Overwrite this method for validation checks used only on updates.
974       def validate_on_update # :doc:
975       end
976   end
977 end
Note: See TracBrowser for help on using the browser.