Issue
I'm using ajv with TypeScript and have a custom type MyCustomType
. When creating a validation schema I want to ensure that a specific property is of type MyCustomType
. So ajv should validate its structure and decide whether this could be parsed to the given type.
I started with the following sample code ( and created a Codesandbox example for testing purposes )
import { AType } from "./AType"; // custom type
import { AnInterface } from "./AnInterface"; // custom interface
import Ajv from "ajv";
type MyComplexType = AType | AnInterface; // create a more complex type from the given imports
const ajvInstance = new Ajv();
const schema = {
type: "object",
properties: {
myComplexType: { type: "string" } // value structure must match structure of MyComplexType
},
required: ["myComplexType"],
additionalProperties: false
};
const validate = ajvInstance.compile(schema);
const data = {
myComplexType: {}
};
const isValid = validate(data);
if (isValid) {
console.info("everything is fine");
} else {
validate.errors?.forEach((error) => console.error(error.message));
}
Currently I don't know how to create a validation schema for the property myComplexType
. I found some discussions
but I don't think these will help because
typeof
just returns"object"
instanceof
won't work for types
So do I have to create a custom keyword ( as described here ) and write my own validation logic ( inspect the object structure ) or are there any things I can already use? How should I configure myComplexType
?
Solution
I don't think you can create a custom type
with this library, maybe you're confusing javascript types with typescript types. So you probably have 2 options: 1) instead of using types you use classes and use instanceof
for validating an instance of your class, e.g.
class MyClass {}
const instanceofDef = require("ajv-keywords/dist/definitions/instanceof")
instanceofDef.CONSTRUCTORS.MyClass = MyClass
ajv.validate({instanceof: "MyClass"}, new MyClass())
or 2) you create a nested schema like this
const schema = {
type: "object",
properties: {
myComplexType: {
type: "object",
properties: {
myProperty: { type: "string" },
myFunction: { type: "function" },
...
}
}
},
required: ["myComplexType"],
additionalProperties: false
};
const validate = ajvInstance.compile(schema);
const data = {
myComplexType: {
myProperty: "Hello World",
myFunction: function(){}
}
};
const isValid = validate(data);
Answered By - Merve Sahin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.