Skip to content

No validation error if invalid JSON string is passed and schema allows empty object (no presence validation) #43

Description

@alexander-e1off

Env: ruby 2.7.1, Rails 6.0.3.2
Modified given example as follows:
Schema (added empty object):

{
  "$schema": "http://json-schema.org/draft-04/schema",
  "oneOf": [
    { "$ref": "#/definitions/profile" },
    { "$ref": "#/definitions/empty" }
  ],
  "definitions": {
  "profile": {
    "type": "object",
    "properties": {
      "city": { "type": "string" },
      "country": { "type": "string" }
    },
    "required": ["country"]
  },
  "empty": {
    "type": "object",
    "properties": {},
    "additionalProperties": false
  }
}

Model (removed 'profile' presence validation):

create_table "users" do |t|
  t.string "name"
  t.json "profile" # First-class JSON with PostgreSQL, yo.
end

class User < ActiveRecord::Base
  # Constants
  PROFILE_JSON_SCHEMA = Rails.root.join('config', 'schemas', 'profile.json_schema').to_s

  # Validations
  validates :name, presence: true
  validates :profile, json: { schema: PROFILE_JSON_SCHEMA }
end

Expected result:

user = User.new(name: 'Samuel Garneau', profile: '{invalid JSON":}')
user.valid? # => false
user.profile_invalid_json # => '{invalid JSON":}'

Observed result:

user = User.new(name: 'Samuel Garneau', profile: '{invalid JSON":}')
user.valid? # => true
user.profile_invalid_json # => '{invalid JSON":}'

Since attribute setter got JSON parsing error, it replaces it with empty object {} which is passed then to validate_each, and if schema supports empty object, validation is passed and no error is added even if "#{attribute}_invalid_json" is not empty.

It seems it is needed to add in the beginning of validate_each method something like:

return record.errors.add(attribute, 'JSON parse error') if record.send(:"#{attribute}_invalid_json").present?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions