Method: ICFS::Validate.string

Defined in:
lib/icfs/validate.rb

.string(obj, val) ⇒ Hash, NilClass

check a string

Parameters:

  • obj (Object)

    object to validate

  • val (Hash)

    options

Options Hash (val):

  • :allowed (#include?)

    Value which is always okay

  • :valid (#match)

    check for okay value

  • :whitelist (Boolean)

    Must be valid or allowed

  • :invalid (#match)

    check for bad values

  • :min (Integer)

    Minimum length

  • :max (Integer)

    Maximum length

Returns:

  • (Hash, NilClass)

    error descriptions



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/icfs/validate.rb', line 200

def self.string(obj, val)

  # type
  return 'not a String'.freeze unless obj.is_a?(String)

  errors = {}

  # good values
  if (val[:allowed] && val[:allowed].include?(obj)) ||
     (val[:valid] && val[:valid].match(obj))
    return nil
  end

  # if whitelisting
  if val[:whitelist]
    errors[:whitelist] = 'Value was not whitelisted'.freeze
  end

  # min length
  if val[:min] && obj.size < val[:min]
    errors[:min] = 'too short: %d < %d' % [obj.size, val[:min]]
  end

  # max length
  if val[:max] && obj.size > val[:max]
    errors[:max] = 'too long: %d > %d' % [obj.size, val[:max]]
  end

  # invalid
  if val[:invalid] && val[:invalid].match(obj)
    errors[:invalid] = true
  end

  return errors.empty? ? nil : errors
end