ajv.addKeyword("isValidString", {
type: "string",
code(cxt) {
const { data, schema, gen } = cxt;
gen.func(
"isValid",
["data"],
`
const external_func = require("./customValidation.js");
return external_func(data);
`
);
cxt.fail(`!isValid(data)`);
},
});
So the above sums up the intent.
The key is this line:
const external_func = require("./customValidation.js");
But the code above doesn’t work.
This is the code it generated:
function validate10(
data,
{ instancePath = "", parentData, parentDataProperty, rootData = data } = {}
) {
let vErrors = null;
let errors = 0;
if (errors === 0) {
if (data && typeof data == "object" && !Array.isArray(data)) {
let missing0;
if (data.username === undefined && (missing0 = "username")) {
validate10.errors = [
{
instancePath,
schemaPath: "#/required",
keyword: "required",
params: { missingProperty: missing0 },
message: "must have required property '" + missing0 + "'",
},
];
return false;
} else {
if (data.username !== undefined) {
const _errs1 = errors;
if (errors === _errs1) {
if (typeof data.username === "string") {
async function isValid(data) {
if (!isValid(data)) {
validate10.errors = [
{
instancePath: instancePath + "/username",
schemaPath: "#/properties/username/isValidString",
keyword: "isValidString",
params: {},
message: 'must pass "isValidString" keyword validation',
},
];
return false;
}
}
} else {
validate10.errors = [
{
instancePath: instancePath + "/username",
schemaPath: "#/properties/username/type",
keyword: "type",
params: { type: "string" },
message: "must be string",
},
];
return false;
}
}
}
}
} else {
validate10.errors = [
{
instancePath,
schemaPath: "#/type",
keyword: "type",
params: { type: "object" },
message: "must be object",
},
];
return false;
}
}
validate10.errors = vErrors;
return errors === 0;
}
In particular, this makes no sense:
async function isValid(data) {
if (!isValid(data)) {
validate10.errors = [
{
instancePath: instancePath + "/username",
schemaPath: "#/properties/username/isValidString",
keyword: "isValidString",
params: {},
message: 'must pass "isValidString" keyword validation',
},
];
return false;
}
}