Class: JsonValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/json_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
# File 'app/validators/json_validator.rb', line 2

def validate_each(record, attribute, value)
  return if value.blank?

  # Allow native Ruby Hash or Array
  return if value.is_a?(Hash) || value.is_a?(Array)

  # Allow valid JSON string (object or array)
  parsed = JSON.parse(value)
  record.errors.add(attribute, 'must be a valid JSON object or array') unless parsed.is_a?(Hash) || parsed.is_a?(Array)
rescue JSON::ParserError
  record.errors.add(attribute, 'must be a valid JSON')
end