How to use z-schema - 10 common examples

To help you get started, we’ve selected a few z-schema examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github json-schema-faker / json-schema-faker / tests / schema / validator.js View on Github external
'idn-email': () => true,
    },
    schemas: fixed,
  });

  if (!v(sample)) {
    // FIXME: https://github.com/mafintosh/is-my-json-valid/issues/172
    if (v.errors[0].field !== 'data.num') {
      v.errors.forEach(e => {
        fail.push(`${e.field.replace('data.', '')} ${e.message}`);
      });
    }
  }

  // z-schema
  const validator = new ZSchema({
    ignoreUnresolvableReferences: true,
  });

  Object.keys(fixed).forEach(k => {
    validator.setRemoteReference(k, fixed[k]);
  });

  let valid;

  try {
    valid = validator.validate(clone(sample), clone(schema));
  } catch (e) {
    fail.push(`[z-schema] ${e.message}`);
  }

  const errors = validator.getLastErrors();
github danhawkes / react-update-server / src / index.js View on Github external
'use strict';

import process from 'process';
import path from 'path';
import ZSchema from "z-schema";
import config from './data/config';
import configSchema from './config_schema.json';
import Server from './Server';

// Validate the config up-front
let validator = new ZSchema();
validator.validate(config, configSchema);
var errors = validator.getLastErrors();
if (errors !== undefined) {
  console.error("Config validation failed:");
  errors.forEach(error => console.error(error));
  process.exit(1);
}

let server = new Server(path.join(__dirname, 'data'));
server.listen(process.env.PORT);

process.on('SIGINT', () => server.close());
github RiseVision / rise-node / packages / core-helpers / src / z_schema.ts View on Github external
if (!Buffer.isBuffer(str)) {
    return false;
  }
  return str.length === 32;
});

z_schema.registerFormat('csv', (str: string) => {
  try {
    const a = str.split(',');
    return a.length > 0 && a.length <= 1000;
  } catch (e) {
    return false;
  }
});

z_schema.registerFormat('signature', (str: string) => {
  return /^[a-f0-9]{128}$/i.test(str);
});

z_schema.registerFormat('signatureBuf', (buf: Buffer) => {
  if (!Buffer.isBuffer(buf)) {
    return false;
  }
  return buf.length === 64;
});

// tslint:disable-next-line no-identical-functions
z_schema.registerFormat('sha256Buf', (buf: Buffer) => {
  if (!Buffer.isBuffer(buf)) {
    return false;
  }
  return buf.length === 32;
github APIDevTools / swagger-parser / lib / validators / schema.js View on Github external
function initializeZSchema () {
  // HACK: Delete the OpenAPI schema IDs because ZSchema can't resolve them
  delete openapi.v2.id;
  delete openapi.v3.id;

  // The OpenAPI 3.0 schema uses "uri-reference" formats.
  // Assume that any non-whitespace string is valid.
  ZSchema.registerFormat("uri-reference", (value) => value.trim().length > 0);

  // Configure ZSchema
  return new ZSchema({
    breakOnFirstError: true,
    noExtraKeywords: true,
    ignoreUnknownFormats: false,
    reportPathAsArray: true
  });
}
github ciena-frost / ember-frost-bunsen / addon / validator / model.js View on Github external
import 'ember-frost-bunsen/typedefs'

import _ from 'lodash'
import ZSchema from 'z-schema'

import {addErrorResult, aggregateResults, ensureJsonObject, validateRequiredAttribute} from './utils'
import dereference from '../dereference'
import customFormats from './custom-formats'

// Register custom formats with z-schema
_.forIn(customFormats, (validator, name) => {
  ZSchema.registerFormat(name, validator)
})

const validator = new ZSchema({
  noTypeless: true,
  forceItems: true
})

/** currently supported model types */
const supportedTypes = ['string', 'object', 'array', 'integer', 'number', 'boolean']

/**
 * Validate the children of the model object (if any exist)
 * @param {String} path - the path to the field from the root of the model
 * @param {BunsenModel} model - the model to validate
 * @returns {BunsenValidationResult} the results of the model validation
 */
function _validateChildren (path, model) {
  const results = [
    {
github LiskHQ / lisk-sdk-examples / framework / src / modules / chain / helpers / z_schema.js View on Github external
const { ACTIVE_DELEGATES, MAX_VOTES_PER_ACCOUNT } = global.constants;
			return (
				Number.isInteger(value) && MAX_VOTES_PER_ACCOUNT <= ACTIVE_DELEGATES
			);
		},
	},
};

// Register the formats
Object.keys(liskFormats).forEach(formatName => {
	z_schema.registerFormat(formatName, liskFormats[formatName]);
});

// Assigned as custom attribute to be used later
// since z_schema.getRegisteredFormats() only returns keys not the methods
z_schema.formatsCache = liskFormats;

// Exports
module.exports = z_schema;
github LiskHQ / lisk-sdk-examples / framework / src / controller / validator / z_schema.js View on Github external
const ZSchema = require('z-schema');
const formats = require('./formats');

// Register the formats
Object.keys(formats).forEach(formatName => {
	ZSchema.registerFormat(formatName, formats[formatName]);
});
ZSchema.formatsCache = formats;

module.exports = ZSchema;
github LiskHQ / lisk-sdk / framework / src / modules / http_api / helpers / z_schema.js View on Github external
const { ACTIVE_DELEGATES, MAX_VOTES_PER_ACCOUNT } = global.constants;
			return (
				Number.isInteger(value) && MAX_VOTES_PER_ACCOUNT <= ACTIVE_DELEGATES
			);
		},
	},
};

// Register the formats
Object.keys(liskFormats).forEach(formatName => {
	z_schema.registerFormat(formatName, liskFormats[formatName]);
});

// Assigned as custom attribute to be used later
// since z_schema.getRegisteredFormats() only returns keys not the methods
z_schema.formatsCache = liskFormats;

// Exports
module.exports = z_schema;
github LiskHQ / lisk-sdk / framework / src / controller / validator / z_schema.js View on Github external
const ZSchema = require('z-schema');
const formats = require('./formats');

// Register the formats
Object.keys(formats).forEach(formatName => {
	ZSchema.registerFormat(formatName, formats[formatName]);
});
ZSchema.formatsCache = formats;

module.exports = ZSchema;
github isa-group / oas-tools / src / middleware / oas-validator.js View on Github external
keepGoing = false;
        } else { // In case the parameter is indeed present, check type. In the case of array, check also type of its items!
          try { // eslint-disable-line
            if (schema.type !== 'string') { // eslint-disable-line
              value = JSON.parse(req[location][name]);
            } else {
              value = String(req[location][name]);
            }
          } catch (err) {
            value = String(req[location][name]);
          }
          err = validator.validate(value, schema);
          if (err == false) {  // eslint-disable-line
            keepGoing = false;
            if (err.code == "UNKNOWN_FORMAT") { // eslint-disable-line
              var registeredFormats = ZSchema.getRegisteredFormats();
              logger.error("UNKNOWN_FORMAT error - Registered Formats: ");
              logger.error(registeredFormats);
            }
            newErr = {
              message: "Wrong parameter " + name + " in " + location + ". ",
              error: validator.getLastErrors()
            };
            msg.push(newErr);
          } else {
            logger.info("Valid parameter on request");
          }
        }
      }
    }
  }
  if (keepGoing == false && config.strict == true) {