-
-
Save rin/d6195b5f80838020ba199d19f108edc7 to your computer and use it in GitHub Desktop.
Custom Validator for JSON in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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