Q:

How to validate the input value of text_area is JSON format?

I am using rails 4.2 with Ruby 2.1.5
Here is my description model:
class Description < ActiveRecord::Base
  validates :value, presence: true
  belongs_to :api
end

What can I do to validate the input of value is JSON format?

A:

add a custom validate method that will parse value.  Just rescue the exception and add an error if it fails parsing.
validate :validate_json_format

private

def validate_json_format
  return if value.blank?

  JSON.parse(value)

rescue JSON::ParserError
  errors.add(:value, 'invalid JSON format')
end

