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



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/coradoc/validation.rb', line 246

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