Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 109 lines (90 sloc) 5.804 kB
87535bd @dhh Splitting them up first
dhh authored
1 module ActiveModel
3ae67fb @rizwanreza Add titles to the rest of the files in active_model/validations/*
rizwanreza authored
2
3 # == Active Model Length Validator
87535bd @dhh Splitting them up first
dhh authored
4 module Validations
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
5 class LengthValidator < EachValidator
977a5c4 @josevalim Added check_validity! to EachValidator and refactor existing ones.
josevalim authored
6 MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
7 CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
8
977a5c4 @josevalim Added check_validity! to EachValidator and refactor existing ones.
josevalim authored
9 DEFAULT_TOKENIZER = lambda { |value| value.split(//) }
0421fb7 @josevalim Refactor previous commit a bit [#4057 state:resolved]
josevalim authored
10 RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
11
12 def initialize(options)
fa14d6d @josevalim Compile length validator options still at the class level, so wheneve…
josevalim authored
13 if range = (options.delete(:in) || options.delete(:within))
14 raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
15 options[:minimum], options[:maximum] = range.begin, range.end
16 options[:maximum] -= 1 if range.exclude_end?
17 end
18
cbe1d24 @amatsuda Don't add DEFAULT_TOKENIZER to every instance of LengthValidator. Jus…
amatsuda authored
19 super
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
20 end
21
977a5c4 @josevalim Added check_validity! to EachValidator and refactor existing ones.
josevalim authored
22 def check_validity!
fa14d6d @josevalim Compile length validator options still at the class level, so wheneve…
josevalim authored
23 keys = CHECKS.keys & options.keys
24
25 if keys.empty?
26 raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
27 end
28
29 keys.each do |key|
30 value = options[key]
31
32 unless value.is_a?(Integer) && value >= 0
33 raise ArgumentError, ":#{key} must be a nonnegative Integer"
34 end
35 end
977a5c4 @josevalim Added check_validity! to EachValidator and refactor existing ones.
josevalim authored
36 end
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored
37
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
38 def validate_each(record, attribute, value)
cbe1d24 @amatsuda Don't add DEFAULT_TOKENIZER to every instance of LengthValidator. Jus…
amatsuda authored
39 value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.kind_of?(String)
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
40
fa14d6d @josevalim Compile length validator options still at the class level, so wheneve…
josevalim authored
41 CHECKS.each do |key, validity_check|
42 next unless check_value = options[key]
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
43
e82b38c @subbarao tidy up validations length code [#5297 state:resolved]
subbarao authored
44 value ||= [] if key == :maximum
157c37f @spastorino Refactor length validation
spastorino authored
45
46 value_length = value.respond_to?(:length) ? value.length : value.to_s.length
47 next if value_length.send(validity_check, check_value)
26392c4 @jeroenvandijk Make ActiveModel::Errors#add_on_blank and #add_on_empty accept an opt…
jeroenvandijk authored
48
f23bc84 @josevalim validates_length_of should not change the options hash in place. [#52…
josevalim authored
49 errors_options = options.except(*RESERVED_OPTIONS)
50 errors_options[:count] = check_value
51
52 default_message = options[MESSAGES[key]]
53 errors_options[:message] ||= default_message if default_message
54
55 record.errors.add(attribute, MESSAGES[key], errors_options)
977a5c4 @josevalim Added check_validity! to EachValidator and refactor existing ones.
josevalim authored
56 end
57 end
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
58 end
59
9131a88 @joshk validation macros can now be used within an instance
joshk authored
60 module HelperMethods
8828b2c @lifo Move all the Active Record validations to Active Model
lifo authored
61
87535bd @dhh Splitting them up first
dhh authored
62 # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
63 #
64 # class Person < ActiveRecord::Base
8e071bc @r00k Change hashrocket spacing to match conventions.
r00k authored
65 # validates_length_of :first_name, :maximum => 30
66 # validates_length_of :last_name, :maximum => 30, :message => "less than 30 if you don't mind"
87535bd @dhh Splitting them up first
dhh authored
67 # validates_length_of :fax, :in => 7..32, :allow_nil => true
68 # validates_length_of :phone, :in => 7..32, :allow_blank => true
69 # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
0fb16d0 @ffmike Clean up documentation on validates_length_of and change overly juven…
ffmike authored
70 # validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least 5 characters"
71 # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with 4 characters... don't play me."
caa8ab0 @vijaydev remove stray (
vijaydev authored
72 # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least 100 words.", :tokenizer => lambda { |str| str.scan(/\w+/) }
87535bd @dhh Splitting them up first
dhh authored
73 # end
74 #
75 # Configuration options:
8828b2c @lifo Move all the Active Record validations to Active Model
lifo authored
76 # * <tt>:minimum</tt> - The minimum size of the attribute.
77 # * <tt>:maximum</tt> - The maximum size of the attribute.
78 # * <tt>:is</tt> - The exact size of the attribute.
79 # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
80 # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
64092de @fxn Improve documentation coverage and markup
fxn authored
81 # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
82 # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
9bd91b0 @lawrencepit Favor %{} in all code instead of (deprecated) {{}} as interpolation s…
lawrencepit authored
83 # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %{count} characters)").
84 # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %{count} characters)").
85 # * <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)").
2a4b780 @smartinez87 Remove extra white spaces on ActiveModel docs.
smartinez87 authored
86 # * <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.
b481574 @fxn copy-edits 8d96b89
fxn authored
87 # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
88 # validation contexts by default (+nil+), other options are <tt>:create</tt>
89 # and <tt>:update</tt>.
64092de @fxn Improve documentation coverage and markup
fxn authored
90 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
2a4b780 @smartinez87 Remove extra white spaces on ActiveModel docs.
smartinez87 authored
91 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
64092de @fxn Improve documentation coverage and markup
fxn authored
92 # method, proc or string should return or evaluate to a true or false value.
93 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
2a4b780 @smartinez87 Remove extra white spaces on ActiveModel docs.
smartinez87 authored
94 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
87535bd @dhh Splitting them up first
dhh authored
95 # method, proc or string should return or evaluate to a true or false value.
8828b2c @lifo Move all the Active Record validations to Active Model
lifo authored
96 # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
97 # count words as in above example.)
98 # Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
8620bf9 @bogdan Implemented strict validation concept
bogdan authored
99 # * <tt>:strict</tt> - Specifies whether validation should be strict.
100 # See <tt>ActiveModel::Validation#validates!</tt> for more information
f1085f4 @josevalim Move validations in ActiveModel to validators, however all validatity…
josevalim authored
101 def validates_length_of(*attr_names)
0a79eb7 @thelucid Add validates method as shortcut to setup validators for a given set …
thelucid authored
102 validates_with LengthValidator, _merge_attributes(attr_names)
87535bd @dhh Splitting them up first
dhh authored
103 end
104
105 alias_method :validates_size_of, :validates_length_of
106 end
107 end
28f3627 @josh Properly require ActiveModel validation dependencies
josh authored
108 end
Something went wrong with that request. Please try again.