root/tags/rel_2-0-2/activerecord/lib/active_record/validations.rb
| Revision 8379, 49.4 kB (checked in by marcel, 1 year ago) | |
|---|---|
| |
| 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 #:nodoc: |
| 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 | end |
| 283 | |
| 284 | # All of the following validations are defined in the class scope of the model that you're interested in validating. |
| 285 | # They offer a more declarative way of specifying when the model is valid and when it is not. It is recommended to use |
| 286 | # these over the low-level calls to validate and validate_on_create when possible. |
| 287 | module ClassMethods |
| 288 | DEFAULT_VALIDATION_OPTIONS = { |
| 289 | :on => :save, |
| 290 | :allow_nil => false, |
| 291 | :allow_blank => false, |
| 292 | :message => nil |
| 293 | }.freeze |
| 294 | |
| 295 | ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze |
| 296 | ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=', |
| 297 | :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=', |
| 298 | :odd => 'odd?', :even => 'even?' }.freeze |
| 299 | |
| 300 | # Adds a validation method or block to the class. This is useful when |
| 301 | # overriding the #validate instance method becomes too unwieldly and |
| 302 | # you're looking for more descriptive declaration of your validations. |
| 303 | # |
| 304 | # This can be done with a symbol pointing to a method: |
| 305 | # |
| 306 | # class Comment < ActiveRecord::Base |
| 307 | # validate :must_be_friends |
| 308 | # |
| 309 | # def must_be_friends |
| 310 | # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee) |
| 311 | # end |
| 312 | # end |
| 313 | # |
| 314 | # Or with a block which is passed the current record to be validated: |
| 315 | # |
| 316 | # class Comment < ActiveRecord::Base |
| 317 | # validate do |comment| |
| 318 | # comment.must_be_friends |
| 319 | # end |
| 320 | # |
| 321 | # def must_be_friends |
| 322 | # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee) |
| 323 | # end |
| 324 | # end |
| 325 | # |
| 326 | # This usage applies to #validate_on_create and #validate_on_update as well. |
| 327 | def validate(*methods, &block) |
| 328 | methods << block if block_given? |
| 329 | write_inheritable_set(:validate, methods) |
| 330 | end |
| 331 | |
| 332 | def validate_on_create(*methods, &block) |
| 333 | methods << block if block_given? |
| 334 | write_inheritable_set(:validate_on_create, methods) |
| 335 | end |
| 336 | |
| 337 | def validate_on_update(*methods, &block) |
| 338 | methods << block if block_given? |
| 339 | write_inheritable_set(:validate_on_update, methods) |
| 340 | end |
| 341 | |
| 342 | def condition_block?(condition) |
| 343 | condition.respond_to?("call") && (condition.arity == 1 || condition.arity == -1) |
| 344 | end |
| 345 | |
| 346 | # Determine from the given condition (whether a block, procedure, method or string) |
| 347 | # whether or not to validate the record. See #validates_each. |
| 348 | def evaluate_condition(condition, record) |
| 349 | case condition |
| 350 | when Symbol; record.send(condition) |
| 351 | when String; eval(condition, record.send(:binding)) |
| 352 | else |
| 353 | if condition_block?(condition) |
| 354 | condition.call(record) |
| 355 | else |
| 356 | raise( |
| 357 | ActiveRecordError, |
| 358 | "Validations need to be either a symbol, string (to be eval'ed), proc/method, or " + |
| 359 | "class implementing a static validation method" |
| 360 | ) |
| 361 | end |
| 362 | end |
| 363 | end |
| 364 | |
| 365 | # Validates each attribute against a block. |
| 366 | # |
| 367 | # class Person < ActiveRecord::Base |
| 368 | # validates_each :first_name, :last_name do |record, attr, value| |
| 369 | # record.errors.add attr, 'starts with z.' if value[0] == ?z |
| 370 | # end |
| 371 | # end |
| 372 | # |
| 373 | # Options: |
| 374 | # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update) |
| 375 | # * <tt>allow_nil</tt> - Skip validation if attribute is nil. |
| 376 | # * <tt>allow_blank</tt> - Skip validation if attribute is blank. |
| 377 | # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 378 | # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The |
| 379 | # method, proc or string should return or evaluate to a true or false value. |
| 380 | # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 381 | # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The |
| 382 | # method, proc or string should return or evaluate to a true or false value. |
| 383 | def validates_each(*attrs) |
| 384 | options = attrs.extract_options!.symbolize_keys |
| 385 | attrs = attrs.flatten |
| 386 | |
| 387 | # Declare the validation. |
| 388 | send(validation_method(options[:on] || :save)) do |record| |
| 389 | # Don't validate when there is an :if condition and that condition is false or there is an :unless condition and that condition is true |
| 390 | unless (options[:if] && !evaluate_condition(options[:if], record)) || (options[:unless] && evaluate_condition(options[:unless], record)) |
| 391 | attrs.each do |attr| |
| 392 | value = record.send(attr) |
| 393 | next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) |
| 394 | yield record, attr, value |
| 395 | end |
| 396 | end |
| 397 | end |
| 398 | end |
| 399 | |
| 400 | # Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example: |
| 401 | # |
| 402 | # Model: |
| 403 | # class Person < ActiveRecord::Base |
| 404 | # validates_confirmation_of :user_name, :password |
| 405 | # validates_confirmation_of :email_address, :message => "should match confirmation" |
| 406 | # end |
| 407 | # |
| 408 | # View: |
| 409 | # <%= password_field "person", "password" %> |
| 410 | # <%= password_field "person", "password_confirmation" %> |
| 411 | # |
| 412 | # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password. |
| 413 | # To achieve this, the validation adds acccessors to the model for the confirmation attribute. NOTE: This check is performed |
| 414 | # only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence |
| 415 | # check for the confirmation attribute: |
| 416 | # |
| 417 | # validates_presence_of :password_confirmation, :if => :password_changed? |
| 418 | # |
| 419 | # Configuration options: |
| 420 | # * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation") |
| 421 | # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update) |
| 422 | # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 423 | # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The |
| 424 | # method, proc or string should return or evaluate to a true or false value. |
| 425 | # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 426 | # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The |
| 427 | # method, proc or string should return or evaluate to a true or false value. |
| 428 | def validates_confirmation_of(*attr_names) |
| 429 | configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save } |
| 430 | configuration.update(attr_names.extract_options!) |
| 431 | |
| 432 | attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" })) |
| 433 | |
| 434 | validates_each(attr_names, configuration) do |record, attr_name, value| |
| 435 | record.errors.add(attr_name, configuration[:message]) unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation") |
| 436 | end |
| 437 | end |
| 438 | |
| 439 | # Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example: |
| 440 | # |
| 441 | # class Person < ActiveRecord::Base |
| 442 | # validates_acceptance_of :terms_of_service |
| 443 | # validates_acceptance_of :eula, :message => "must be abided" |
| 444 | # end |
| 445 | # |
| 446 | # If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is |
| 447 | # performed only if terms_of_service is not nil and by default on save. |
| 448 | # |
| 449 | # Configuration options: |
| 450 | # * <tt>message</tt> - A custom error message (default is: "must be accepted") |
| 451 | # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update) |
| 452 | # * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true) |
| 453 | # * <tt>accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which |
| 454 | # makes it easy to relate to an HTML checkbox. This should be set to 'true' if you are validating a database |
| 455 | # column, since the attribute is typecast from "1" to <tt>true</tt> before validation. |
| 456 | # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 457 | # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The |
| 458 | # method, proc or string should return or evaluate to a true or false value. |
| 459 | # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 460 | # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The |
| 461 | # method, proc or string should return or evaluate to a true or false value. |
| 462 | def validates_acceptance_of(*attr_names) |
| 463 | configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" } |
| 464 | configuration.update(attr_names.extract_options!) |
| 465 | |
| 466 | db_cols = begin |
| 467 | column_names |
| 468 | rescue ActiveRecord::StatementInvalid |
| 469 | [] |
| 470 | end |
| 471 | names = attr_names.reject { |name| db_cols.include?(name.to_s) } |
| 472 | attr_accessor(*names) |
| 473 | |
| 474 | validates_each(attr_names,configuration) do |record, attr_name, value| |
| 475 | record.errors.add(attr_name, configuration[:message]) unless value == configuration[:accept] |
| 476 | end |
| 477 | end |
| 478 | |
| 479 | # Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example: |
| 480 | # |
| 481 | # class Person < ActiveRecord::Base |
| 482 | # validates_presence_of :first_name |
| 483 | # end |
| 484 | # |
| 485 | # The first_name attribute must be in the object and it cannot be blank. |
| 486 | # |
| 487 | # If you want to validate the presence of a boolean field (where the real values are true and false), |
| 488 | # you will want to use validates_inclusion_of :field_name, :in => [true, false] |
| 489 | # This is due to the way Object#blank? handles boolean values. false.blank? # => true |
| 490 | # |
| 491 | # Configuration options: |
| 492 | # * <tt>message</tt> - A custom error message (default is: "can't be blank") |
| 493 | # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update) |
| 494 | # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 495 | # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The |
| 496 | # method, proc or string should return or evaluate to a true or false value. |
| 497 | # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 498 | # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The |
| 499 | # method, proc or string should return or evaluate to a true or false value. |
| 500 | # |
| 501 | # === Warning |
| 502 | # Validate the presence of the foreign key, not the instance variable itself. |
| 503 | # Do this: |
| 504 | # validates_presence_of :invoice_id |
| 505 | # |
| 506 | # Not this: |
| 507 | # validates_presence_of :invoice |
| 508 | # |
| 509 | # If you validate the presence of the associated object, you will get |
| 510 | # failures on saves when both the parent object and the child object are |
| 511 | # new. |
| 512 | def validates_presence_of(*attr_names) |
| 513 | configuration = { :message => ActiveRecord::Errors.default_error_messages[:blank], :on => :save } |
| 514 | configuration.update(attr_names.extract_options!) |
| 515 | |
| 516 | # can't use validates_each here, because it cannot cope with nonexistent attributes, |
| 517 | # while errors.add_on_empty can |
| 518 | send(validation_method(configuration[:on])) do |record| |
| 519 | unless (configuration[:if] && !evaluate_condition(configuration[:if], record)) || (configuration[:unless] && evaluate_condition(configuration[:unless], record)) |
| 520 | record.errors.add_on_blank(attr_names, configuration[:message]) |
| 521 | end |
| 522 | end |
| 523 | end |
| 524 | |
| 525 | # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time: |
| 526 | # |
| 527 | # class Person < ActiveRecord::Base |
| 528 | # validates_length_of :first_name, :maximum=>30 |
| 529 | # validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind" |
| 530 | # validates_length_of :fax, :in => 7..32, :allow_nil => true |
| 531 | # validates_length_of :phone, :in => 7..32, :allow_blank => true |
| 532 | # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name" |
| 533 | # validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character" |
| 534 | # validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me." |
| 535 | # end |
| 536 | # |
| 537 | # Configuration options: |
| 538 | # * <tt>minimum</tt> - The minimum size of the attribute |
| 539 | # * <tt>maximum</tt> - The maximum size of the attribute |
| 540 | # * <tt>is</tt> - The exact size of the attribute |
| 541 | # * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute |
| 542 | # * <tt>in</tt> - A synonym(or alias) for :within |
| 543 | # * <tt>allow_nil</tt> - Attribute may be nil; skip validation. |
| 544 | # * <tt>allow_blank</tt> - Attribute may be blank; skip validation. |
| 545 | # |
| 546 | # * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)") |
| 547 | # * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)") |
| 548 | # * <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)") |
| 549 | # * <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 |
| 550 | # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update) |
| 551 | # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 552 | # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The |
| 553 | # method, proc or string should return or evaluate to a true or false value. |
| 554 | # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should |
| 555 | # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The |
| 556 | # method, proc or string should return or evaluate to a true or false value. |
| 557 | def validates_length_of(*attrs) |
| 558 | # Merge given options with defaults. |
| 559 | options = { |
| 560 | :too_long => ActiveRecord::Errors.default_error_messages[:too_long], |
| 561 | :too_short => ActiveRecord::Errors.default_error_messages[:too_short], |
| 562 | :wrong_length => ActiveRecord::Errors.default_error_messages[:wrong_length] |
| 563 | }.merge(DEFAULT_VALIDATION_OPTIONS) |
| 564 | options.update(attrs.extract_options |