Class: LengthValidationRule

Inherits:
ValidationRule show all
Defined in:
lib/validation_profiler/rules/rules.rb

Instance Method Summary collapse

Methods inherited from ValidationRule

#get_field_value, #is_required?

Instance Method Details

#error_message(field, attributes) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/validation_profiler/rules/rules.rb', line 87

def error_message(field, attributes)
  #check if a custom error message has been specified in the attributes
  if attributes[:message] == nil
    #no custom error message has been specified so create the default message.
    min = attributes[:min]
    max = attributes[:max]
    if min && max
      "#{field} must have a min length of #{min} and a max length of #{max}"
    elsif min
      "#{field} must have a min length of #{min}"
    else
      "#{field} must have a max length of #{max}"
    end
  else
    attributes[:message]
  end
end

#validate(obj, field, attributes) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/validation_profiler/rules/rules.rb', line 105

def validate(obj, field, attributes)

  min = attributes[:min]
  max = attributes[:max]

  #verify the expected attributes have been specified.
  if min == nil && max == nil
    raise InvalidRuleAttributes.new(LengthValidationRule, field)
  end

  #attempt to get the field value from the object
  field_value = get_field_value(obj, field)

  #check if this validation check should be skipped
  if !is_required?(field_value, attributes)
    return true
  end

  if field_value.is_a?(Array)
    length = field_value.length
  else
    length = field_value.to_s.length
  end

  #validate the field value
  if min && max
    return length >= min && length <= max
  elsif min
    return length >= min
  elsif max
    return length <= max
  end

  return false
end