Method: JSONValidate.validate

Defined in:
lib/json_validate.rb

.validate(json, validator = nil, path = [], &block) ⇒ Object

Validate the parsed JSON object with the validator validator can be a hash or an array

e.g. {id: Fixnum, subject: String, message: String, receipients: [{email: String, name: String}]}
e.g. [String]

This throws a ValidationError if the validation failed. If a block is given, validator is ignored and the block is evaluated as the validator to be used



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/json_validate.rb', line 41

def self.validate(json, validator=nil, path=[], &block)
  return validate(json, JSONValidate.instance_eval(&block), path) if block_given?

  case validator
  when Hash # validate each pair of the hash
    validateHash(json, validator, path)
  when Array # validate each elements of the array
    validateArray(json, validator, path)
  when Class # validate the type of the value
    raise ValidationError.new(pathstr(path)) unless json.kind_of? validator
  when CustomValidator
    raise ValidationError.new(pathstr(path)) unless validator.validate(json)
  when Regexp
    raise ValidationError.new(pathstr(path)) unless validator =~ json
  when nil
    raise ValidationError.new(pathstr(path)) unless json.nil?
  else
    raise ValidationError.new("Validator is expected to be Hash, Array, or Class.")
  end
end