Created
April 13, 2017 11:25
-
-
Save anonymous/5e64ab161a220a6be4b0cc5385b346b0 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