Module: Padrino::Validation::HTML5

Defined in:
lib/padrino/validation/html5.rb,
lib/padrino/validation/html5/version.rb

Defined Under Namespace

Modules: ExtendedHelpers

Constant Summary collapse

VERSION =
"0.2"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(subj) ⇒ Object



31
32
33
34
35
# File 'lib/padrino/validation/html5.rb', line 31

def included(subj)
  subj.field_types.each {|field|
    define_method(field) {|field, options={}| options = inject_validations(field, options); super(field, options) }
  }
end

.registered(app) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/padrino/validation/html5.rb', line 20

def registered(app)
  builder = Padrino::Helpers::FormBuilder.const_get(app.settings.default_builder)
  builder.send :include, self
  Padrino::Helpers::TagHelpers.instance_eval do
    alias_method :__identity_tag_attributes, :identity_tag_attributes
    def identity_tag_attributes
      __identity_tag_attributes + [:readonly, :required, :autofocus, :novalidate, :formnovalidate, :multiple]
    end
  end
end

Instance Method Details

#inject_validations(field, options = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/padrino/validation/html5.rb', line 38

def inject_validations(field, options={})
  validators = object.class.validators_on(field).
    group_by(&:kind).
    map {|kind, validators| [kind, validators.map(&:options).inject(&:merge)] }
  validators.each do |kind, opts|
    case kind
    when :presence
      options.reverse_merge!(required: true)
    when :length
      attrs = {}
      if opts[:is]
        attrs[:minlength] = attrs[:maxlength] = opts[:is]
      else
        attrs[:minlength] = [opts[:minimum], opts[:within].try(:first)].compact.max
        attrs[:maxlength] = [opts[:maximum], opts[:within].try(:last)].compact.min
      end
      options.reverse_merge!(attrs.reject {|_, v| v.blank? })
    when :inclusion
      if opts[:in].respond_to?(:first) && opts[:in].respond_to?(:last)
        attrs = {
          min: opts[:in].first,
          max: opts[:in].last
        }
        options.reverse_merge!(attrs.reject {|_, v| v.blank? })
      end
    end
  end
  options
end