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



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/coradoc/validation.rb', line 286

def validate(element, _context = {})
  field = options[:field]
  value = field_value(element, field)

  return [] if value.nil?

  errors = []
  length = value.is_a?(String) ? 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