You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
JsonValidator is an ActiveModel validator that validates any hash field against [JSONSchema](http://json-schema.org), returning errors in the model's own `errors` attribute.
@@ -18,7 +18,7 @@ If you're using Ruby on Rails and ActiveRecord, add a validation to your model l
18
18
~~~ruby
19
19
classFoo < ActiveRecord::Base
20
20
validates :bar, json: {
21
-
schema:File.read(JSON.parse('foo_schema.json'))
21
+
schema:JSON.parse(File.read('foo_schema.json'))
22
22
}
23
23
end
24
24
~~~
@@ -27,7 +27,7 @@ And you have a schema file (ie. `foo_schema.json`) like this:
@@ -39,6 +39,14 @@ And you have a schema file (ie. `foo_schema.json`) like this:
39
39
}
40
40
~~~
41
41
42
-
Then whenever an instance of `Foo` is saved, `Foo.bar` (assumed to be a hash) will be validated against the JSON schema specified. In this case, `Foo.new(bar: { handleSize: -10 })` would be invalid, but `Foo.new(bar: { handleSize: 10 })` would be valid.
42
+
Then whenever an instance of `Foo` is saved, `Foo.bar` (assumed to be a hash) will be validated against the JSON schema specified. So, for example:
43
+
44
+
~~~ruby
45
+
46
+
f =Foo.new(bar: { handleSize:-10 })
47
+
f.valid? # false
48
+
f.errors.full_messages # ["Bar is invalid (the property '#/handleSize' did not have a minimum value of 0, inclusively)"]
49
+
50
+
~~~
43
51
44
52
The attribute being validated can be either a hash or a string (which will be parsed as JSON). The schema can be either a hash or a Proc that returns a hash (if you'd like to decide on the schema at runtime), and there's no reason why you could not load your schema from a .json file.
0 commit comments