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

  • require("ajv-keywords")(ajv, "transform");
    
    const schema = {
      type: "array",
      items: {
        type: "string",
        transform: ["trim", "toLowerCase"],
      },
    };
    
    const data = ["  MixCase  "];
    ajv.validate(schema, data);
    console.log(data); // ['mixcase']
    
    Docs
    0
  • require("ajv-keywords")(ajv, ["transform"]);
    
    const schema = {
      type: "array",
      items: {
        type: "string",
        transform: ["trim", "toEnumCase"],
        enum: ["pH"],
      },
    };
    
    const data = ["ph", " Ph", "PH", "pH "];
    ajv.validate(schema, data);
    console.log(data); // ['pH','pH','pH','pH']
    
    Docs
    0
  • require('ajv-keywords')(ajv, 'select');
    
    const schema = {
      type: "object",
      required: ['kind'],
      properties: {
        kind: { type: 'string' }
      },
      select: { $data: '0/kind' },
      selectCases: {
        foo: {
          required: ['foo'],
          properties: {
            kind: {},
            foo: { type: 'string' }
          },
          additionalProperties: false
        },
        bar: {
          required: ['bar'],
          properties: {
            kind: {},
            bar: { type: 'number' }
          },
          additionalProperties: false
        }
      },
      selectDefault: {
        propertyNames: {
          not: { enum: ['foo', 'bar'] }
        }
      }
    };
    
    const validDataList = [
      { kind: 'foo', foo: 'any' },
      { kind: 'bar', bar: 1 },
      { kind: 'anything_else', not_bar_or_foo: 'any value' }
    ];
    
    const invalidDataList = [
      { kind: 'foo' }, // no property foo
      { kind: 'bar' }, // no property bar
      { kind: 'foo', foo: 'any', another: 'any value' }, // additional property
      { kind: 'bar', bar: 1, another: 'any value' }, // additional property
      { kind: 'anything_else', foo: 'any' } // property foo not allowed
      { kind: 'anything_else', bar: 1 } // property bar not allowed
    ];
    
    Docs
    0
  • require("ajv-keywords")(ajv, "instanceof");
    
    Docs
    0
  • const Ajv = require("ajv");
    const ajv = new Ajv();
    require("ajv-keywords")(ajv);
    
    ajv.validate({ instanceof: "RegExp" }, /.*/); // true
    ajv.validate({ instanceof: "RegExp" }, ".*"); // false
    
    Docs
    0
  • const ajv = new Ajv({
      keywords: require("ajv-keywords/dist/definitions")(opts),
    });
    
    Docs
    0
  • require("ajv-keywords")(ajv, ["typeof", "instanceof"]);
    
    Docs
    0
  • const ajv = new Ajv({
      keywords: [
        require("ajv-keywords/dist/definitions/typeof")(),
        require("ajv-keywords/dist/definitions/instanceof")(),
        // select exports an array of 3 definitions - see "select" in docs
        ...require("ajv-keywords/dist/definitions/select")(
          opts
        ),
      ],
    });
    
    Docs
    0
  • require("ajv-keywords")(ajv, "transform");
    
    const schema = {
      type: "array",
      items: {
        type: "string",
        transform: ["trim", "toLowerCase"],
      },
    };
    
    const data = ["  MixCase  "];
    ajv.validate(schema, data);
    console.log(data); // ['mixcase']
    
    Docs
    0
  • const schema = { type: "number", range: [1, 3] };
    ajv.validate(schema, 1); // true
    ajv.validate(schema, 2); // true
    ajv.validate(schema, 3); // true
    ajv.validate(schema, 0.99); // false
    ajv.validate(schema, 3.01); // false
    
    const schema = { type: "number", exclusiveRange: [1, 3] };
    ajv.validate(schema, 1.01); // true
    ajv.validate(schema, 2); // true
    ajv.validate(schema, 2.99); // true
    ajv.validate(schema, 1); // false
    ajv.validate(schema, 3); // false
    
    Docs
    0
  • require("ajv-keywords")(ajv, ["transform"]);
    
    const schema = {
      type: "array",
      items: {
        type: "string",
        transform: ["trim", "toEnumCase"],
        enum: ["pH"],
      },
    };
    
    const data = ["ph", " Ph", "PH", "pH "];
    ajv.validate(schema, data);
    console.log(data); // ['pH','pH','pH','pH']
    
    Docs
    0
  • const schema = {
      type: "object",
      dynamicDefaults: {
        ts: "datetime",
        r: { func: "randomint", args: { max: 100 } },
        id: { func: "seq", args: { name: "id" } },
      },
      properties: {
        ts: {
          type: "string",
          format: "date-time",
        },
        r: {
          type: "integer",
          minimum: 0,
          exclusiveMaximum: 100,
        },
        id: {
          type: "integer",
          minimum: 0,
        },
      },
    };
    
    const data = {};
    ajv.validate(data); // true
    data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 }
    
    const data1 = {};
    ajv.validate(data1); // true
    data1; // { ts: '2016-12-01T22:07:29.832Z', r: 68, id: 1 }
    
    ajv.validate(data1); // true
    data1; // didn't change, as all properties were defined
    
    Docs
    0
  • ajv.validate({ instanceof: "Array" }, []); // true
    ajv.validate({ instanceof: "Array" }, {}); // false
    ajv.validate(
      { instanceof: ["Array", "Function"] },
      function () {}
    ); // true
    
    Docs
    0
  • const schema = {
      type: "object",
      allOf: [
        {
          dynamicDefaults: {
            ts: "datetime",
            r: {
              func: "randomint",
              args: { min: 5, max: 100 },
            },
            id: { func: "seq", args: { name: "id" } },
          },
        },
        {
          properties: {
            ts: {
              type: "string",
            },
            r: {
              type: "number",
              minimum: 5,
              exclusiveMaximum: 100,
            },
            id: {
              type: "integer",
              minimum: 0,
            },
          },
        },
      ],
    };
    
    const data = { ts: "", r: null };
    ajv.validate(data); // true
    data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 }
    
    Docs
    0
  • ajv.validate({ typeof: "undefined" }, undefined); // true
    ajv.validate({ typeof: "undefined" }, null); // false
    ajv.validate({ typeof: ["undefined", "object"] }, null); // true
    
    Docs
    0
  • class MyClass {}
    const instanceofDef = require("ajv-keywords/dist/definitions/instanceof");
    instanceofDef.CONSTRUCTORS.MyClass = MyClass;
    ajv.validate({ instanceof: "MyClass" }, new MyClass()); // true
    
    Docs
    0
  • const uuid = require("uuid");
    
    const def = require("ajv-keywords/dist/definitions/dynamicDefaults");
    def.DEFAULTS.uuid = () => uuid.v4;
    
    const schema = {
      dynamicDefaults: { id: "uuid" },
      properties: { id: { type: "string", format: "uuid" } },
    };
    
    const data = {};
    ajv.validate(schema, data); // true
    data; // { id: 'a1183fbe-697b-4030-9bcc-cfeb282a9150' };
    
    const data1 = {};
    ajv.validate(schema, data1); // true
    data1; // { id: '5b008de7-1669-467a-a5c6-70fa244d7209' }
    
    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({ processCode: transpileFunc });
    const validate = ajv.compile(schema); // transpiled es7 async function
    validate(data).then(successFunc).catch(errorFunc);
    
    Docs
    1
  • 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({ 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
  • Powered by Official black Bloop logo with a period
    download the IDE extension

    View other examples