How to use where clause in Knex
Create refunds with Stripe
Load HTML with Cheerio
How to send POST request with Axios
Find intersection of array in Lodash
Powered by Official white Bloop logo with a period

Terms / Privacy / Search / Support

  • const Ajv = require("ajv").default;
    const schema_user = require("./schema_user.json");
    const ajv = new Ajv();
    const validate_user = ajv.compile(schema_user);
    
    // this is just some abstract API framework
    app.post("/user", async (cxt) => {
      if (validate_user(cxt.body)) {
        // create user
      } else {
        // report error
        cxt.status(400);
      }
    });
    
    Docs
    0
  • const { default: Ajv, _ } = require("ajv");
    const ajv = new Ajv({
      code: { formats: _`require("./my_formats")` },
    });
    
    Docs
    0
  • import Ajv from "ajv";
    import * as schema_user from "./schema_user.json";
    import * as schema_document from "./schema_document.json";
    export const ajv = new Ajv();
    ajv.addSchema(schema_user, "user");
    ajv.addSchema(schema_document, "document");
    
    Docs
    1
  • const ajv = new Ajv({ coerceTypes: "array" });
    const schema = {
      properties: {
        foo: { type: "array", items: { type: "number" } },
        bar: { type: "boolean" },
      },
    };
    
    const data = { foo: "1", bar: ["false"] };
    
    const validate = ajv.compile(schema);
    
    console.log(validate(data)); // true
    console.log(data); // { "foo": [1], "bar": false }
    
    Docs
    1
  • const ajv = new Ajv();
    const validate = ajv.addSchema(defsSchema).compile(schema);
    
    Docs
    1
  • const ajv = new Ajv({ processCode: transpileFunc });
    const validate = ajv.compile(schema); // transpiled es7 async function
    validate(data).then(successFunc).catch(errorFunc);
    
    Docs
    1
  • const ajv = new Ajv({ allErrors: true });
    
    Docs
    0
  • const ajv = new Ajv()
    
    ajv.addKeyword({
      keyword: "idExists"
      async: true,
      type: "number",
      validate: checkIdExists,
    })
    
    async function checkIdExists(schema, data) {
      // this is just an example, you would want to avoid SQL injection in your code
      const rows = await sql(`SELECT id FROM ${schema.table} WHERE id = ${data}`)
      return !!rows.length // true if record is found
    }
    
    const schema = {
      $async: true,
      properties: {
        userId: {
          type: "integer",
          idExists: {table: "users"},
        },
        postId: {
          type: "integer",
          idExists: {table: "posts"},
        },
      },
    }
    
    const validate = ajv.compile(schema)
    
    validate({userId: 1, postId: 19})
      .then(function (data) {
        console.log("Data is valid", data) // { userId: 1, postId: 19 }
      })
      .catch(function (err) {
        if (!(err instanceof Ajv.ValidationError)) throw err
        // data is invalid
        console.log("Validation errors:", err.errors)
      })
    
    Docs
    0
  • const ajv = new Ajv({ removeAdditional: true });
    const schema = {
      additionalProperties: false,
      properties: {
        foo: { type: "number" },
        bar: {
          additionalProperties: { type: "number" },
          properties: {
            baz: { type: "string" },
          },
        },
      },
    };
    
    const data = {
      foo: 0,
      additional1: 1, // will be removed; `additionalProperties` == false
      bar: {
        baz: "abc",
        additional2: 2, // will NOT be removed; `additionalProperties` != false
      },
    };
    
    const validate = ajv.compile(schema);
    
    console.log(validate(data)); // true
    console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 }
    
    Docs
    0
  • const ajv = new Ajv({ code: { es5: true } });
    
    Docs
    0
  • const ajv = new Ajv({ useDefaults: true });
    const schema = {
      type: "object",
      properties: {
        foo: { type: "number" },
        bar: { type: "string", default: "baz" },
      },
      required: ["foo", "bar"],
    };
    
    const data = { foo: 1 };
    
    const validate = ajv.compile(schema);
    
    console.log(validate(data)); // true
    console.log(data); // { "foo": 1, "bar": "baz" }
    
    Docs
    0
  • const Ajv = require("ajv");
    const ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
    
    const schema = {
      type: "object",
      properties: {
        foo: { type: "integer" },
        bar: { type: "string" },
      },
      required: ["foo"],
      additionalProperties: false,
    };
    
    const validate = ajv.compile(schema);
    
    const data = {
      foo: 1,
      bar: "abc",
    };
    
    const valid = validate(data);
    if (!valid) console.log(validate.errors);
    
    Docs
    0
  • const Ajv = require("ajv");
    const ajv = new Ajv();
    
    Docs
    0
  • import Ajv from "ajv";
    import * as draft6MetaSchema from "ajv/dist/refs/json-schema-draft-06.json";
    
    const ajv = new Ajv();
    ajv.addMetaSchema(draft6MetaSchema);
    
    Docs
    0
  • const Ajv = require("ajv");
    const addFormats = require("ajv-formats");
    
    const ajv = new Ajv();
    addFormats(ajv);
    
    Docs
    0
  • import myFormats from "./my-formats";
    import Ajv, { _ } from "ajv";
    const ajv = new Ajv({
      formats: myFormats,
      code: {
        source: true,
        formats: _`require("./my-formats")`,
      },
    });
    
    Docs
    0
  • const Ajv = require("ajv");
    const draft6MetaSchema = require("ajv/dist/refs/json-schema-draft-06.json");
    
    const ajv = new Ajv();
    ajv.addMetaSchema(draft6MetaSchema);
    
    Docs
    0
  • import Ajv from "ajv";
    import * as schema_user from "./schema_user.json";
    const ajv = new Ajv();
    const validate_user = ajv.compile(schema_user);
    
    interface User {
      username: string;
    }
    
    // this is just some abstract API framework
    app.post("/user", async (cxt) => {
      if (validate_user(cxt.body)) {
        // create user
      } else {
        // report error
        cxt.status(400);
      }
    });
    
    Docs
    0
  • const ajv = new Ajv();
    const validate = ajv.compile(schema);
    if (validate(data)) {
      // data is MyData here
      // ...
    } else {
      // DefinedError is a type for all pre-defined keywords errors,
      // validate.errors has type ErrorObject[] - to allow user-defined keywords with any error parameters.
      // Users can extend DefinedError to include the keywords errors they defined.
      for (const err of validate.errors as DefinedError[]) {
        switch (err.keyword) {
          case "maximum":
            console.log(err.limit);
            break;
          case "pattern":
            console.log(err.pattern);
            break;
          // ...
        }
      }
    }
    
    Docs
    0
  • const ajv = new Ajv({ loadSchema: loadSchema });
    
    ajv.compileAsync(schema).then(function (validate) {
      const valid = validate(data);
      // ...
    });
    
    async function loadSchema(uri) {
      const res = await request.json(uri);
      if (res.statusCode >= 400)
        throw new Error("Loading error: " + res.statusCode);
      return res.body;
    }
    
    Docs
    0
  • const ajv = new Ajv({ coerceTypes: true });
    const schema = {
      type: "object",
      properties: {
        foo: { type: "number" },
        bar: { type: "boolean" },
      },
      required: ["foo", "bar"],
    };
    
    const data = { foo: "1", bar: "false" };
    
    const validate = ajv.compile(schema);
    
    console.log(validate(data)); // true
    console.log(data); // { "foo": 1, "bar": false }
    
    Docs
    0
  • const Ajv = require("ajv");
    const schema_user = require("./schema_user.json");
    const schema_document = require("./schema_document.json");
    const ajv = (exports.ajv = new Ajv());
    ajv.addSchema(schema_user, "user");
    ajv.addSchema(schema_document, "document");
    
    Docs
    0
  • const Ajv = require("ajv"); // version >= v7.0.0
    const ajv = new Ajv({ code: { source: true } }); // this option is required to generate standalone code
    const standaloneCode = require("ajv/dist/standalone");
    
    const schema = {
      $id: "https://example.com/object.json",
      type: "object",
      properties: {
        foo: {
          type: "string",
          pattern: "^[a-z]+$",
        },
      },
    };
    
    // 1. generate module with a single default export (CommonJS and ESM compatible):
    const validate = ajv.compile(schema);
    let moduleCode = standaloneCode(ajv, validate);
    
    // 2. pass map of schema IDs to generate multiple exports,
    // it avoids code duplication if schemas are mutually recursive or have some share elements:
    let moduleCode = standaloneCode(ajv, {
      validateObject: "https://example.com/object.json",
    });
    
    // 3. or generate module with all schemas added to the instance (excluding meta-schemas),
    // export names would use schema IDs (or keys passed to addSchema method):
    let moduleCode = standaloneCode(ajv);
    
    // now you can
    // write module code to file
    const fs = require("fs");
    const path = require("path");
    fs.writeFileSync(
      path.join(__dirname, "/validate.js"),
      moduleCode
    );
    
    // ... or require module from string
    const requireFromString = require("require-from-string");
    const standaloneValidate = requireFromString(moduleCode); // for a single default export
    
    Docs
    0
  • import Ajv from "ajv";
    import addFormats from "ajv-formats";
    
    const ajv = new Ajv();
    addFormats(ajv);
    
    Docs
    0
  • import Ajv, { JSONSchemaType } from "ajv";
    const ajv = new Ajv();
    
    type MyUnion = { prop: boolean } | string | number;
    
    const schema: JSONSchemaType = {
      anyOf: [
        {
          type: "object",
          properties: { prop: { type: "boolean" } },
          required: ["prop"],
        },
        {
          type: ["string", "number"],
        },
      ],
    };
    
    Docs
    0
  • const ajv = new Ajv({ $data: true });
    
    const schema = {
      properties: {
        smaller: {
          type: "number",
          maximum: { $data: "1/larger" },
        },
        larger: { type: "number" },
      },
    };
    
    const validData = {
      smaller: 5,
      larger: 7,
    };
    
    ajv.validate(schema, validData); // true
    
    Docs
    0
  • import Ajv, { JSONSchemaType } from "ajv";
    const ajv = new Ajv();
    
    interface MyData {
      foo: number;
      bar?: string;
    }
    
    const schema: JSONSchemaType = {
      type: "object",
      properties: {
        foo: { type: "integer" },
        bar: { type: "string", nullable: true },
      },
      required: ["foo"],
      additionalProperties: false,
    };
    
    // validate is a type guard for MyData - type is inferred from schema type
    const validate = ajv.compile(schema);
    
    // or, if you did not use type annotation for the schema,
    // type parameter can be used to make it type guard:
    // const validate = ajv.compile(schema)
    
    const data = {
      foo: 1,
      bar: "abc",
    };
    
    if (validate(data)) {
      // data is MyData here
      console.log(data.foo);
    } else {
      console.log(validate.errors);
    }
    
    Docs
    0
  • const ajv = new Ajv({ schemas: [schema, defsSchema] });
    const validate = ajv.getSchema(
      "http://example.com/schemas/schema.json"
    );
    
    Docs
    0
  • const otherLogger = new OtherLogger();
    const ajv = new Ajv({
      logger: {
        log: console.log.bind(console),
        warn: function warn() {
          otherLogger.logWarn.apply(otherLogger, arguments);
        },
        error: function error() {
          otherLogger.logError.apply(otherLogger, arguments);
          console.error.apply(console, arguments);
        },
      },
    });
    
    Docs
    0
  • const ajv = new Ajv();
    
    Docs
    0
  • import Ajv from "ajv";
    const ajv = new Ajv();
    
    Docs
    0
  • import Ajv, { _ } from "ajv";
    const ajv = new Ajv({
      code: { formats: _`require("./my_formats")` },
    });
    
    Docs
    0
  • const validate = new Ajv()
      .addSchema(schema)
      .addFormat(name, regex)
      .getSchema(uri);
    
    Docs
    -1
  • import Ajv, { _ } from "ajv";
    const ajv = new Ajv({
      code: { formats: _`require("./my_formats")` },
    });
    
    Docs
    0
  • import myFormats from "./my-formats";
    import Ajv, { _ } from "ajv";
    const ajv = new Ajv({
      formats: myFormats,
      code: {
        source: true,
        formats: _`require("./my-formats")`,
      },
    });
    
    Docs
    0
  • const { default: Ajv, _ } = require("ajv");
    const ajv = new Ajv({
      code: { formats: _`require("./my_formats")` },
    });
    
    Docs
    0
  • const Ajv = require("ajv").default;
    const ajv = new Ajv({ allErrors: true });
    // Ajv option allErrors is required
    require("ajv-errors")(ajv /*, {singleError: true} */);
    
    Docs
    0
  • import Ajv from "ajv";
    import * as schema_user from "./schema_user.json";
    import * as schema_document from "./schema_document.json";
    export const ajv = new Ajv();
    ajv.addSchema(schema_user, "user");
    ajv.addSchema(schema_document, "document");
    
    Docs
    1
  • const ajv = new Ajv();
    const validate = ajv.addSchema(defsSchema).compile(schema);
    
    Docs
    1
  • parser
      .dereference(
        path.resolve("src/backend/schema/index.json")
      )
      .then((schema) => {
        ajv.addSchema(schema);
        return schema;
      });
    
    /jc21/juxtapose mit
    0
  • const validate = new Ajv()
      .addSchema(schema)
      .addFormat(name, regex)
      .getSchema(uri);
    
    Docs
    -1
  • Powered by Official black Bloop logo with a period
    download the IDE extension

    View other examples