How to validate if a string is json in a Rails model

前端 未结 7 667
悲&欢浪女
悲&欢浪女 2021-01-31 16:03

I\'m building a simple app and want to be able to store json strings in a db. I have a table Interface with a column json, and I want my rails model to validate the value of the

7条回答
  •  既然无缘
    2021-01-31 16:58

    Using JSON parser, pure JSON format validation is possible. ActiveSupport::JSON.decode(value) validates value "123" and 123 to true. That is not correct!

    # 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)
        if value.is_a?(Hash) || value.is_a?(Array)
          value = value.to_json
        elsif value.is_a?(String)
          value = value.strip
        end
        JSON.parse(value)
      rescue JSON::ParserError, TypeError => exception
        record.errors.add(attribute, options[:message], exception_message: exception.message)
      end
    
    end
    

提交回复
热议问题