Skip to content

Instantly share code, notes, and snippets.

@rin
Forked from anonymous/my_object.rb
Created April 13, 2017 11:25
Show Gist options
  • Save rin/d6195b5f80838020ba199d19f108edc7 to your computer and use it in GitHub Desktop.
Save rin/d6195b5f80838020ba199d19f108edc7 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