I am trying to use jsonschema-master to validate a json request entered via a POST request using express. See the code and sample below.
It picks up if the attribute labels are missing or spelt wrong, such as “model”, “areas”, “id” but isn’t picking up if the values of those attributes meet the specifications. For example the “model” attribute is defined as an enumerated type either “premium” or “basic”, but I seem to be able to put any old string in there and it plows on regardless, also the coordinates are defined as type number, but again it ignores this and the error then gets passed the validator and causes problems further on. Not sure what I'm missing.
node.js code:
var Validator = require('jsonschema-master').Validator;
var v = new Validator();
var bodySchema = {
"model": {
"enum": [ "premium","basic" ]
},
"areas": {
"type":"array",
"items": {
"id": {"type": "string"},
"geometry": {
"type": { "type":"string"},
"coordinates": {
"type":"array",
"items": {
"type":"array",
"items": [
{"type":"number"},
{"type":"number"},
{"type":"number"}
]
}
},
"required" : ["type","coordinates"]
},
"required" : ["id","geometry"]
}
},
"required" : ["model","areas"]
};
var valResult = v.validate(doc.request, bodySchema);
if (valResult.errors.length) {
// Validation failed.
// All processing will now stop.
console.log('Request invalid: '+ doc._id +" - "+valResult.errors);
}
SAMPLE CORRECT JSON request (in doc.request)
{
"model": "premium",
"areas": [
{
"id": "1234",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
453600.0,
181100.0,
0
],
[
453600.0,
181200.0,
0
],
[
453700.0,
181200.0,
0
],
[
453700.0,
181100.0,
0
],
[
453600.0,
181100.0,
0
]
]
]
}
}
]
}
Thanks all, but I worked it out in the end. Here is the corrected syntax for the schema:
var bodySchema = {
"type" : "object",
"properties": {
"model": {
"enum": [ "premium","basic" ]
},
"areas": {
"type":"array",
"items": {
"type" : "object",
"properties": {
"id": {"type": "string"},
"geometry": {
"type" : "object",
"properties": {
"type": { "type":"string"},
"coordinates": {
"type":"array",
"items": {
"type":"array",
"items": {
"type":"array",
"items": [
{"type":"number"},
{"type":"number"},
{"type":"number"}
]
}
}
}
},
"required" : ["type","coordinates"]
}
},
"required" : ["id","geometry"]
}
}
},
"required" : ["model","areas"]
};
Related
I have a complex object that I need to validate in parts (each part is validated by a different party). I guess I can create a schema file per each part, but I really want to be able to use one file.
For example, my schema could be the following, and I want to be able to validate an object against obj1.
I'm trying to figure out a standard way of defining such a situation and what I can expect from implementations. Not looking necessarily for a specific library. But if some libraries support this and some don't, I'm interested in Javascript ones.
{
"required": [
"prop1",
"another",
"obj1",
"obj2"
],
"properties": {
"prop1": {
"type": "integer"
},
"another": {
"type": "string"
},
"obj1": {
"$ref": "#/$defs/obj1"
},
"obj2": {
"type": "object",
"required": [
"foo"
],
"properties": {
"foo": {
"type": "string"
}
}
}
},
"$defs": {
"obj1": {
"type": "object",
"required": [
"sub1",
"sub2",
"a_number"
],
"properties": {
"sub1": {
"type": "string"
},
"sub2": {
"type": "string"
},
"a_number": {
"type": "integer"
}
}
}
}
}
const personData= {
name: null,
email: 'test#gmail.com'
}
const schema = {
instance: personData,
schema: {
type: "object",
anyOf: [
{ required: ["name", "email"] }
]
}
}
I want a schema which will validate the object and from object any of the key value (name or email) where one of them must be not null.
It looks like you're confused between "undefined" and "null", which are distinctly different. (I've now edited your question in light of your comment on my answer.)
The required keyword makes sure that a key is "defined" in the applicable object. The value is irrelevant, and may be null.
If you want to define the TYPE of a property, you have to use the type keyword.
anyOf must be an array of schemas where at least one of them must be true.
You've defined one subschema in the anyOf, and as a result, it must be true as a whole, making both items in the required array, required.
You want to define multiple schemas under your anyOf, where one each schema defines that a property must be of a specific type (null is a type).
{
"type": "object",
"required": ["name", "email"],
"anyOf": [
{
"properties": {
"name": {
"type": "string"
}
}
}, {
"properties": {
"email": {
"type": "string"
}
}
}
]
}
You can solve this by placing the 'required' property under the anyof list
{
"type": "object",
"anyOf": [
{
"required": ["name"],
"properties": {
"name": {
"type": "string"
}
}
}, {
"required": ["email"],
"properties": {
"email": {
"type": "string"
}
}
}
]
}
The required attribute means you must have a property in data. It may be nullable, though. To exclude null values make sure that anyOf properties you need are not null:
"anyOf": [
{
"properties": {
"name": {
"not": {
"type": "null"
}
}
}
},
{
"properties": {
"email": {
"not": {
"type": "null"
}
}
}
}
]
Full version goes below:
{
"type": "object",
"properties": {
"name": {
"type": [
"string",
"null"
]
},
"email": {
"type": [
"string",
"null"
]
}
},
"required": [
"name",
"email"
],
"anyOf": [
{
"properties": {
"name": {
"not": {
"type": "null"
}
}
}
},
{
"properties": {
"email": {
"not": {
"type": "null"
}
}
}
}
]
}
Given:
Say that I am defining a schema for Contacts. But, I can have "Primary Contact", "Student" or one who is both; and different properties that go with all three choices. The contact types are defined in an array of contact_type: [ "Primary Contact", "Student" ] which can be either one, or both.
Say that the fields are as such per contact type:
If Primary Contact, then I want phone_number
If Student, then I want first_name
If Student and Primary Contact then I want phone_number and first_name
Usage
I use Ajv library to validate in Node.js using a code like such:
function validator(json_schema){
const Ajv = require('ajv');
const ajv = new Ajv({allErrors: true});
return ajv.compile(json_schema)
}
const validate = validator(json_schema);
const valid = validate(input);
console.log(!!valid); //true or false
console.log(validate.errors)// object or null
Note: I've had trouble with allErrors: true while using anyOf for this, and I use the output of allErrors to return ALL the missing/invalid fields back to the user rather than returning problems one at a time. Reference: https://github.com/ajv-validator/ajv/issues/980
Schema
I have written the following schema and it works if I do either "Student" or "Primary Contact" but when I pass both, it still wants to validate against ["Student"] or ["Primary Contact"] rather than both.
{
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"required": [],
"properties": {},
"allOf": [
{
"if": {
"properties": {
"contact_type": {
"contains": {
"allOf": [
{
"type": "string",
"const": "Primary Contact"
},
{
"type": "string",
"const": "Student"
}
]
}
}
}
},
"then": {
"additionalProperties": false,
"properties": {
"contact_type": {
"type": "array",
"items": [
{
"type": "string",
"enum": [
"Student",
"Primary Contact"
]
}
]
},
"phone": {
"type": "string"
},
"first_name": {
"type": "string"
}
},
"required": [
"phone",
"first_name"
]
}
},
{
"if": {
"properties": {
"contact_type": {
"contains": {
"type": "string",
"const": "Student"
}
}
}
},
"then": {
"additionalProperties": false,
"properties": {
"contact_type": {
"type": "array",
"items": [
{
"type": "string",
"enum": [
"Student",
"Primary Contact"
]
}
]
},
"first_name": {
"type": "string"
}
},
"required": [
"first_name"
]
}
},
{
"if": {
"properties": {
"contact_type": {
"contains": {
"type": "string",
"const": "Primary Contact"
}
}
}
},
"then": {
"additionalProperties": false,
"properties": {
"contact_type": {
"type": "array",
"items": [
{
"type": "string",
"enum": [
"Student",
"Primary Contact"
]
}
]
},
"phone": {
"type": "string"
}
},
"required": [
"phone"
]
}
}
]
}
Example Valid Inputs:
For just ["Primary Contact"]:
{
"contact_type":["Primary Contact"],
"phone":"something"
}
For just ["Student"]:
{
"contact_type":["Student"],
"first_name":"something"
}
For ["Primary Contact", "Student"]
{
"contact_type":["Primary Contact", "Student"],
"phone":"something",
"first_name":"something"
}
Question:
I would like this to validate even if allErrors: true, is this possible? If not, how should I change the schema?
Footnotes
I don't want to change the "contact_type" from being an array unless it is the last resort. (it is a requirement, but can be broken only if there's no other way)
I can't allow any additionalItems, therefore I'm fully defining each object in the if statements although contact_type is common. If I move contact_type out, then I get error messages about passing contact_type as an additionalItem (it looks at the if statement's properties and doesn't see contact_type when it's taken out to the common place). This is why my initial properties object is empty.
Here's how I might go about solving the validation issue: https://jsonschema.dev/s/XLSDB
Here's the Schema...
(It's easier if you try to break up concerns)
{
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
First, we want to define our conditional checking subschemas...
"definitions": {
"is_student": {
"properties": {
"contact_type": {
"contains": {
"const": "Student"
}
}
}
},
"is_primay_contact": {
"properties": {
"contact_type": {
"contains": {
"const": "Primary Contact"
}
}
}
}
},
Next, I'm assuming you always want contact_type
"required": ["contact_type"],
"properties": {
"contact_type": {
"type": "array",
"items": {
"enum": ["Primary Contact", "Student"]
}
},
And we need to define all the allowed properties in order to prevent additional properties. (draft-07 cannot "see through" applicator keywords like allOf. You can with draft 2019-09 and beyond, but that's another story)
"phone": true,
"first_name": true
},
"additionalProperties": false,
Now, we need to define our structural constraints...
"allOf": [
{
If the contact is a student, first name is required.
"if": { "$ref": "#/definitions/is_student" },
"then": { "required": ["first_name"] }
},
{
If the contact is a primary contact, then phone is required.
"if": { "$ref": "#/definitions/is_primay_contact" },
"then": { "required": ["phone"] }
},
{
However, additionally, if the contact is both a student and a primary contact...
"if": {
"allOf": [
{ "$ref": "#/definitions/is_student" },
{ "$ref": "#/definitions/is_primay_contact" }
]
},
Then we require both phone and first name...
"then": {
"required": ["phone", "first_name"]
},
Otherwise, one of phone or first name is fine (which one is covered by the previous section)
"else": {
"oneOf": [
{
"required": ["phone"]
},
{
"required": ["first_name"]
}
]
}
}
]
}
I'm not convinced this is the cleanest approach, but it does work for the requirements you've provided.
As for getting validation errors you can pass back to your END user... given the conditional requirements you lay out, it's not something you can expect with pure JSON Schema...
Having said that, ajv does provide an extension to add custom error messages, which given the way I've broken the validation down into concerns, might be useable to add custom errors as you're looking to do (https://github.com/ajv-validator/ajv-errors).
This is my json file
"type": "FeatureCollection",
"name": "maps",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "IDLo": "1", "SoHieu": "1-1", "KyHieu": "C", "TenLo": "C1-1", "TenCty": "CMC Data Center"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 106.791800519464871, 10.854928689692501 ], [ 106.792069337729856, 10.855930098557222 ], [ 106.792653322236532, 10.855766231881775 ], [ 106.79231961680415, 10.854783029941672 ], [ 106.791800519464871, 10.854928689692501 ] ] ] } },
{ "type": "Feature", "properties": { "IDLo": "2", "SoHieu": "1-2", "KyHieu": "C", "TenLo": "C1-2", "TenCty": "ASCENDAS" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 106.79264868743887, 10.855779887550094 ], [ 106.792064702932166, 10.855943754285464 ], [ 106.791786615071828, 10.854942345054598 ], [ 106.79101723865827, 10.855151730898562 ], [ 106.790461062937595, 10.855306494254153 ], [ 106.789969774384346, 10.855424842648457 ], [ 106.789478485831097, 10.855688850436046 ], [ 106.78819928167357, 10.857819111634392 ], [ 106.790915273109462, 10.859412245764197 ], [ 106.791907119811313, 10.857746282442497 ], [ 106.792111050908886, 10.857518691103408 ], [ 106.792379869173871, 10.857291099590915 ], [ 106.792583800271444, 10.856999782201919 ], [ 106.792732113796944, 10.856544598212894 ], [ 106.792741383392297, 10.856116724630859 ], [ 106.79264868743887, 10.855779887550094 ] ] ] } }]
I want to autocomplete search on features.properties.TenCty
And this is the javascript
jQuery(document).ready(function($) {
$('#cty').autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: "data/maps.json",
dataType: 'json',
data: request,
success: function(data) {
$.each(data.features, function(d){
response($.map(d.properties, function(item) {
console.log(item.TenCty);
return (item.TenCty);
}));
})
}
});
},
minLength: 2
});
});
But I can't get anything, the console like this XHR finished loading: GET "http://localhost:81/blog/data/maps.json?term=fd".
I don't know where is the error. Please help.
Thank you very much.
Basically, you have to update success callback to:
success: function(data) {
var result = $.each(data.features, function(d) {
return (d.properties.TenCty);
})
response(result)
}
However you can revisit JQuery UI Autocomplete Remove JsonP code samples.
I am trying to make an array, where each element contains select. My code right now:
angular.module('MaterialAidForm', ['schemaForm']).controller('FormController', function($scope) {
$scope.schema = {
"type": "object",
"title": "Comment",
"required": [
"comments"
],
"properties": {
"comments": {
"type": "array",
"items": {
"type": "object",
"properties": {
"spam": {
"title": "Spam",
"type": "select",
"titleMap":
{
"a": "A",
"b": "B"
}
}
},
"required": [
"name",
"comment"
]
}
}
}
};
$scope.form = ["*"];
$scope.model = {};
});
But when I open browser, I only see array without selector inside.