Class: Coradoc::Validation::Rules::Length

Inherits:
Coradoc::Validation::Rule show all
Defined in:
lib/coradoc/validation.rb

Overview

Length validation

Instance Attribute Summary

Attributes inherited from Coradoc::Validation::Rule

#name, #options

Instance Method Summary collapse

Methods inherited from Coradoc::Validation::Rule

#initialize

Constructor Details

This class inherits a constructor from Coradoc::Validation::Rule

Instance Method Details

#validate(element, _context = {}) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/coradoc/validation.rb', line 237

def validate(element, _context = {})
  field = options[:field]
  value = element.send(field) if element.respond_to?(field)

  return [] if value.nil?

  errors = []
  length = value.respond_to?(:length) ? value.length : 0

  errors << "#{field} must have at least #{options[:min]} characters/items" if options[:min] && length < options[:min]

  errors << "#{field} must have at most #{options[:max]} characters/items" if options[:max] && length > options[:max]

  errors
end