Module: NForm::Validations
- Included in:
- Form
- Defined in:
- lib/nform/validations.rb
Overview
A Module of simple validation methods. Including objects are required to implement a simple API:
-
Keys passed in to a validation must match instance method names
-
Objects must provide an errors object which responds to []
When called, validators will return true/false indicating whether the validation passed or failed
Instance Method Summary collapse
- #errors ⇒ Object
- #validate_confirmation_of(attribute) ⇒ Object
- #validate_length_of(key, length) ⇒ Object
- #validate_numericality_of(*keys) ⇒ Object
- #validate_presence_of(*keys) ⇒ Object
Instance Method Details
#errors ⇒ Object
10 11 12 |
# File 'lib/nform/validations.rb', line 10 def errors @errors ||= {} end |
#validate_confirmation_of(attribute) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/nform/validations.rb', line 49 def validate_confirmation_of(attribute) confirm_key = attribute.to_s.concat("_confirmation").to_sym if !respond_to?(confirm_key) errors[attribute] = "#{attribute.to_s.humanize} requires confirmation" false elsif send(attribute) != send(confirm_key) errors[confirm_key] = "#{attribute.to_s.humanize} confirmation does not match" false else true end end |
#validate_length_of(key, length) ⇒ Object
39 40 41 42 43 44 45 46 47 |
# File 'lib/nform/validations.rb', line 39 def validate_length_of(key,length) val = send(key) if val && val.respond_to?(:length) && val.length >= length true else errors[key] = "#{key.to_s.humanize} must be at least #{length} characters long" false end end |
#validate_numericality_of(*keys) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/nform/validations.rb', line 25 def validate_numericality_of(*keys) pass = true keys.each do |key| val = send(key) return true if val.is_a?(Numeric) unless (val.respond_to?(:to_i) || val.respond_to?(:to_f)) && (val == val.to_i.to_s || val == val.to_f.to_s) errors[key] = "#{key.to_s.humanize} must be a number" pass = false end end pass end |
#validate_presence_of(*keys) ⇒ Object
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/nform/validations.rb', line 14 def validate_presence_of(*keys) pass = true keys.each do |key| unless respond_to?(key) && send(key) && send(key) != "" errors[key] = "#{key.to_s.humanize} is required" pass = false end end pass end |