Skip to content

Instantly share code, notes, and snippets.

Created April 13, 2017 11:25
Show Gist options
  • Save anonymous/5e64ab161a220a6be4b0cc5385b346b0 to your computer and use it in GitHub Desktop.
Save anonymous/5e64ab161a220a6be4b0cc5385b346b0 to your computer and use it in GitHub Desktop.
Custom Validator for JSON in Rails
class MyObject < ActiveRecord::Base
class JsonValidator < ActiveModel::EachValidator
def initialize(options)
options.reverse_merge!(:message => :invalid)
super(options)
end
def validate_each(record, attribute_before_typecast, value)
attribute = attribute_before_typecast.to_s.sub('_before_type_cast', '')
value = value.strip if value.is_a?(String)
JSON.parse(value)
rescue JSON::ParserError, TypeError => exception
record.errors.add(attribute, options[:message], exception_message: exception.message)
end
end
validates :my_json_field_before_type_cast, presence: true, json: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment