Skip to content

Instantly share code, notes, and snippets.

@joost
Created March 26, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joost/7ee5fbcc40e377369351 to your computer and use it in GitHub Desktop.
Save joost/7ee5fbcc40e377369351 to your computer and use it in GitHub Desktop.
Rails 3 / Rails 4 JSON validator
# Put this code in lib/validators/json_validator.rb
# Usage in your model:
# validates :json_attribute, presence: true, json: true
#
# To have a detailed error use something like:
# validates :json_attribute, presence: true, json: {message: :some_i18n_key}
# In your yaml use:
# some_i18n_key: "detailed exception message: %{exception_message}"
class JsonValidator < ActiveModel::EachValidator
def initialize(options)
options.reverse_merge!(:message => :invalid)
super(options)
end
def validate_each(record, attribute, value)
value = value.strip if value.is_a?(String)
ActiveSupport::JSON.decode(value)
rescue MultiJson::LoadError, TypeError => exception
record.errors.add(attribute, options[:message], exception_message: exception.message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment