Module | Sequel::Plugins::ValidationClassMethods::ClassMethods
In: | lib/sequel/plugins/validation_class_methods.rb

### Methods

has_validations? skip_superclass_validations skip_superclass_validations? validate validates validates_acceptance_of validates_confirmation_of validates_each validates_format_of validates_inclusion_of validates_length_of validates_not_string validates_numericality_of validates_presence_of validates_uniqueness_of validations

### Classes and Modules

Class Sequel::Plugins::ValidationClassMethods::ClassMethods::Generator

### Public Instance methods

has_validations?()

Returns true if validations are defined.

[Source]

        # File lib/sequel/plugins/validation_class_methods.rb, line 23
    23:         def has_validations?
    24:           !validations.empty?
    25:         end

skip_superclass_validations()

Instructs the model to skip validations defined in superclasses

[Source]

        # File lib/sequel/plugins/validation_class_methods.rb, line 28
    28:         def skip_superclass_validations
    29:           @skip_superclass_validations = true
    30:         end

skip_superclass_validations?()

Instructs the model to skip validations defined in superclasses

[Source]

        # File lib/sequel/plugins/validation_class_methods.rb, line 33
    33:         def skip_superclass_validations?
    34:           defined?(@skip_superclass_validations) && @skip_superclass_validations
    35:         end

validate(o)

Validates the given instance.

[Source]

        # File lib/sequel/plugins/validation_class_methods.rb, line 57
    57:         def validate(o)
    58:           superclass.validate(o) if superclass.respond_to?(:validate) && !skip_superclass_validations?
    59:           validations.each do |att, procs|
    60:             v = case att
    61:             when Array
    62:               att.collect{|a| o.send(a)}
    63:             else
    64:               o.send(att)
    65:             end
    66:             procs.each {|tag, p| p.call(o, att, v)}
    67:           end
    68:         end

validates(&block)

Defines validations by converting a longhand block into a series of shorthand definitions. For example:

      class MyClass < Sequel::Model
        validates do
          length_of :name, :minimum => 6
          length_of :password, :minimum => 8
        end
      end

is equivalent to:

      class MyClass < Sequel::Model
        validates_length_of :name, :minimum => 6
        validates_length_of :password, :minimum => 8
      end

[Source]

        # File lib/sequel/plugins/validation_class_methods.rb, line 52
    52:         def validates(&block)
    53:           Generator.new(self, &block)
    54:         end

validates_acceptance_of(*atts)

Validates acceptance of an attribute. Just checks that the value is equal to the :accept option. This method is unique in that :allow_nil is assumed to be true instead of false.

Possible Options:

- :accept - The value required for the object to be valid (default: ‘1’)
- :message - The message to use (default: ‘is not accepted’)

[Source]

        # File lib/sequel/plugins/validation_class_methods.rb, line 77
    77:         def validates_acceptance_of(*atts)
    78:           opts = {
    79:             :message => 'is not accepted',
    80:             :allow_nil => true,
    81:             :accept => '1',
    82:             :tag => :acceptance,
    83:           }.merge!(extract_options!(atts))
    84:           atts << opts
    85:           validates_each(*atts) do |o, a, v|
    86:             o.errors.add(a, opts[:message]) unless v == opts[:accept]
    87:           end
    88:         end

validates_confirmation_of(*atts)

Validates confirmation of an attribute. Checks that the object has a _confirmation value matching the current value. For example:

      validates_confirmation_of :blah

Just makes sure that object.blah = object.blah_confirmation. Often used for passwords or email addresses on web forms.

Possible Options:

- :message - The message to use (default: ‘is not confirmed’)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 100
    100:         def validates_confirmation_of(*atts)
    101:           opts = {
    102:             :message => 'is not confirmed',
    103:             :tag => :confirmation,
    104:           }.merge!(extract_options!(atts))
    105:           atts << opts
    106:           validates_each(*atts) do |o, a, v|
    107:             o.errors.add(a, opts[:message]) unless v == o.send("#{a}_confirmation""#{a}_confirmation")
    108:           end
    109:         end

validates_each(*atts, &block)

Adds a validation for each of the given attributes using the supplied block. The block must accept three arguments: instance, attribute and value, e.g.:

      validates_each :name, :password do |object, attribute, value|
        object.errors.add(attribute, 'is not nice') unless value.nice?
      end

Possible Options:

- :allow_blank - Whether to skip the validation if the value is blank.
- :allow_missing - Whether to skip the validation if the attribute isn‘t a key in the values hash. This is different from allow_nil, because Sequel only sends the attributes in the values when doing an insert or update. If the attribute is not present, Sequel doesn‘t specify it, so the database will use the table‘s default value. This is different from having an attribute in values with a value of nil, which Sequel will send as NULL. If your database table has a non NULL default, this may be a good option to use. You don‘t want to use allow_nil, because if the attribute is in values but has a value nil, Sequel will attempt to insert a NULL value into the database, instead of using the database‘s default.
- :allow_nil - Whether to skip the validation if the value is nil.
- :if - A symbol (indicating an instance_method) or proc (which is instance_evaled) skipping this validation if it returns nil or false.
- :tag - The tag to use for this validation.

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 134
    134:         def validates_each(*atts, &block)
    135:           opts = extract_options!(atts)
    136:           blk = if (i = opts[:if]) || (am = opts[:allow_missing]) || (an = opts[:allow_nil]) || (ab = opts[:allow_blank])
    137:             proc do |o,a,v|
    138:               next if i && !validation_if_proc(o, i)
    139:               next if an && Array(v).all?{|x| x.nil?}
    140:               next if ab && Array(v).all?{|x| x.blank?}
    141:               next if am && Array(a).all?{|x| !o.values.has_key?(x)}
    142:               block.call(o,a,v)
    143:             end
    144:           else
    145:             block
    146:           end
    147:           tag = opts[:tag]
    148:           atts.each do |a|
    149:             a_vals = validations[a]
    150:             if tag && (old = a_vals.find{|x| x[0] == tag})
    151:               old[1] = blk
    152:             else
    153:               a_vals << [tag, blk]
    154:             end
    155:           end
    156:         end

validates_format_of(*atts)

Validates the format of an attribute, checking the string representation of the value against the regular expression provided by the :with option.

Possible Options:

- :message - The message to use (default: ‘is invalid’)
- :with - The regular expression to validate the value with (required).

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 164
    164:         def validates_format_of(*atts)
    165:           opts = {
    166:             :message => 'is invalid',
    167:             :tag => :format,
    168:           }.merge!(extract_options!(atts))
    169:
    170:           unless opts[:with].is_a?(Regexp)
    171:             raise ArgumentError, "A regular expression must be supplied as the :with option of the options hash"
    172:           end
    173:
    174:           atts << opts
    175:           validates_each(*atts) do |o, a, v|
    176:             o.errors.add(a, opts[:message]) unless v.to_s =~ opts[:with]
    177:           end
    178:         end

validates_inclusion_of(*atts)

Validates that an attribute is within a specified range or set of values.

Possible Options:

- :in - An array or range of values to check for validity (required)
- :message - The message to use (default: ‘is not in range or set: <specified range>’)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 290
    290:         def validates_inclusion_of(*atts)
    291:           opts = extract_options!(atts)
    292:           unless opts[:in] && opts[:in].respond_to?(:include?)
    293:             raise ArgumentError, "The :in parameter is required, and respond to include?"
    294:           end
    295:           opts[:message] ||= "is not in range or set: #{opts[:in].inspect}"
    296:           atts << opts
    297:           validates_each(*atts) do |o, a, v|
    298:             o.errors.add(a, opts[:message]) unless opts[:in].include?(v)
    299:           end
    300:         end

validates_length_of(*atts)

Validates the length of an attribute.

Possible Options:

- :is - The exact size required for the value to be valid (no default)
- :maximum - The maximum size allowed for the value (no default)
- :message - The message to use (no default, overrides :too_long, :too_short, and :wrong_length options if present)
- :minimum - The minimum size allowed for the value (no default)
- :too_long - The message to use use if it the value is too long (default: ‘is too long’)
- :too_short - The message to use use if it the value is too short (default: ‘is too short’)
- :within - The array/range that must include the size of the value for it to be valid (no default)
- :wrong_length - The message to use use if it the value is not valid (default: ‘is the wrong length’)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 192
    192:         def validates_length_of(*atts)
    193:           opts = {
    194:             :too_long     => 'is too long',
    195:             :too_short    => 'is too short',
    196:             :wrong_length => 'is the wrong length'
    197:           }.merge!(extract_options!(atts))
    198:
    199:           opts[:tag] ||= ([:length] + [:maximum, :minimum, :is, :within].reject{|x| !opts.include?(x)}).join('-').to_sym
    200:           atts << opts
    201:           validates_each(*atts) do |o, a, v|
    202:             if m = opts[:maximum]
    203:               o.errors.add(a, opts[:message] || opts[:too_long]) unless v && v.size <= m
    204:             end
    205:             if m = opts[:minimum]
    206:               o.errors.add(a, opts[:message] || opts[:too_short]) unless v && v.size >= m
    207:             end
    208:             if i = opts[:is]
    209:               o.errors.add(a, opts[:message] || opts[:wrong_length]) unless v && v.size == i
    210:             end
    211:             if w = opts[:within]
    212:               o.errors.add(a, opts[:message] || opts[:wrong_length]) unless v && w.include?(v.size)
    213:             end
    214:           end
    215:         end

validates_not_string(*atts)

Validates whether an attribute is not a string. This is generally useful in conjunction with raise_on_typecast_failure = false, where you are passing in string values for non-string attributes (such as numbers and dates). If typecasting fails (invalid number or date), the value of the attribute will be a string in an invalid format, and if typecasting succeeds, the value will not be a string.

Possible Options:

- :message - The message to use (default: ‘is a string’ or ‘is not a valid (integer|datetime|etc.)’ if the type is known)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 226
    226:         def validates_not_string(*atts)
    227:           opts = {
    228:             :tag => :not_string,
    229:           }.merge!(extract_options!(atts))
    230:           atts << opts
    231:           validates_each(*atts) do |o, a, v|
    232:             if v.is_a?(String)
    233:               unless message = opts[:message]
    234:                 message = if sch = o.db_schema[a] and typ = sch[:type]
    235:                   "is not a valid #{typ}"
    236:                 else
    237:                   "is a string"
    238:                 end
    239:               end
    240:               o.errors.add(a, message)
    241:             end
    242:           end
    243:         end

validates_numericality_of(*atts)

Validates whether an attribute is a number.

Possible Options:

- :message - The message to use (default: ‘is not a number’)
- :only_integer - Whether only integers are valid values (default: false)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 250
    250:         def validates_numericality_of(*atts)
    251:           opts = {
    252:             :message => 'is not a number',
    253:             :tag => :numericality,
    254:           }.merge!(extract_options!(atts))
    255:           atts << opts
    256:           validates_each(*atts) do |o, a, v|
    257:             begin
    258:               if opts[:only_integer]
    259:                 Kernel.Integer(v.to_s)
    260:               else
    261:                 Kernel.Float(v.to_s)
    262:               end
    263:             rescue
    264:               o.errors.add(a, opts[:message])
    265:             end
    266:           end
    267:         end

validates_presence_of(*atts)

Validates the presence of an attribute. Requires the value not be blank, with false considered present instead of absent.

Possible Options:

- :message - The message to use (default: ‘is not present’)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 274
    274:         def validates_presence_of(*atts)
    275:           opts = {
    276:             :message => 'is not present',
    277:             :tag => :presence,
    278:           }.merge!(extract_options!(atts))
    279:           atts << opts
    280:           validates_each(*atts) do |o, a, v|
    281:             o.errors.add(a, opts[:message]) if v.blank? && v != false
    282:           end
    283:         end

validates_uniqueness_of(*atts)

Validates only if the fields in the model (specified by atts) are unique in the database. Pass an array of fields instead of multiple fields to specify that the combination of fields must be unique, instead of that each field should have a unique value.

This means that the code:

      validates_uniqueness_of([:column1, :column2])

validates the grouping of column1 and column2 while

      validates_uniqueness_of(:column1, :column2)

validates them separately.

You should also add a unique index in the database, as this suffers from a fairly obvious race condition.

Possible Options:

- :message - The message to use (default: ‘is already taken’)

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 318
    318:         def validates_uniqueness_of(*atts)
    319:           opts = {
    320:             :message => 'is already taken',
    321:             :tag => :uniqueness,
    322:           }.merge!(extract_options!(atts))
    323:
    324:           atts << opts
    325:           validates_each(*atts) do |o, a, v|
    326:             error_field = a
    327:             a = Array(a)
    328:             v = Array(v)
    329:             ds = o.class.filter(a.zip(v))
    330:             num_dups = ds.count
    331:             allow = if num_dups == 0
    332:               # No unique value in the database
    333:               true
    334:             elsif num_dups > 1
    335:               # Multiple "unique" values in the database!!
    336:               # Someone didn't add a unique index
    337:               false
    338:             elsif o.new?
    339:               # New record, but unique value already exists in the database
    340:               false
    341:             elsif ds.first === o
    342:               # Unique value exists in database, but for the same record, so the update won't cause a duplicate record
    343:               true
    344:             else
    345:               false
    346:             end
    347:             o.errors.add(error_field, opts[:message]) unless allow
    348:           end
    349:         end

validations()

Returns the validations hash for the class.

[Source]

         # File lib/sequel/plugins/validation_class_methods.rb, line 352
    352:         def validations
    353:           @validations ||= Hash.new {|h, k| h[k] = []}
    354:         end

[Validate]