How to use the jsonschema.Validator function in jsonschema

To help you get started, we’ve selected a few jsonschema 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 department-of-veterans-affairs / vets-website / test / edu-benefits / 1990e / schema / schema.unit.spec.js View on Github external
describe('1990e schema tests', () => {
  const v = new Validator();
  const files = fs.readdirSync(__dirname);
  files
    .filter(file => file.endsWith('json'))
    .forEach((file) => {
      it(`should validate ${file}`, () => {
        const contents = JSON.parse(fs.readFileSync(path.join(__dirname, file), 'utf8'));
        const submitData = JSON.parse(transform(formConfig, contents)).educationBenefitsClaim.form;
        const result = v.validate(
          JSON.parse(submitData),
          fullSchema1990e
        );
        if (!result.valid) {
          console.log(result.errors); // eslint-disable-line
        }
        expect(result.valid).to.be.true;
      });
github exratione / cloudformation-deploy / lib / configValidator.js View on Github external
required: true
    },

    progressCheckIntervalInSeconds: {
      type: 'number',
      minimum: 1,
      required: true
    }
  }
});

// --------------------------------------------------------------------------
// Set up the validator.
// --------------------------------------------------------------------------

var validator = new jsonschema.Validator();

/**
 * Since jsonschema doesn't seem to test function types properly at this point
 * in time, hack in an additional test.
 */
validator.attributes.isFunction = function (instance, schema, options, ctx) {
  var result = new jsonschema.ValidatorResult(instance, schema, options, ctx);

  if (!_.isBoolean(schema.isFunction)) {
    return result;
  }

  if (schema.isFunction) {
    if ((instance !== undefined) && (typeof instance !== 'function')) {
      result.addError('Required to be a function.');
    }
github ripple / ripple-lib / src / common / schema-validator.ts View on Github external
require('./schemas/input/prepare-payment-channel-claim.json'),
    require('./schemas/input/prepare-check-create.json'),
    require('./schemas/input/prepare-check-cash.json'),
    require('./schemas/input/prepare-check-cancel.json'),
    require('./schemas/input/compute-ledger-hash.json'),
    require('./schemas/input/sign.json'),
    require('./schemas/input/submit.json'),
    require('./schemas/input/generate-address.json'),
    require('./schemas/input/sign-payment-channel-claim.json'),
    require('./schemas/input/verify-payment-channel-claim.json'),
    require('./schemas/input/combine.json')
  ]
  const titles = schemas.map(schema => schema.title)
  const duplicates = _.keys(_.pickBy(_.countBy(titles), count => count > 1))
  assert.ok(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates)
  const validator = new Validator()
  // Register custom format validators that ignore undefined instances
  // since jsonschema will still call the format validator on a missing
  // (optional)  property

  // This relies on "format": "xAddress" in `x-address.json`!
  validator.customFormats.xAddress = function(instance) {
    if (instance === undefined) {
      return true
    }
    return isValidXAddress(instance)
  }

  // This relies on "format": "classicAddress" in `classic-address.json`!
  validator.customFormats.classicAddress = function(instance) {
    if (instance === undefined) {
      return true
github mrvautin / openKB / routes / api.js View on Github external
router.post('/api/newArticle', (req, res) => {
    const db = req.app.db;
    const lunr_index = req.app.index;
    const v = new Validator();

    // if API is not set or set to false we stop it
    if(typeof config.settings.api_allowed === 'undefined' || config.settings.api_allowed === false){
        res.status(400).json({ result: false, errors: ['Not allowed'] });
        return;
    }

    // if API token is not set or set to an empty value we stop it. Accidently allowing a public API with no token is no 'toke'.
    if(typeof config.settings.api_auth_token === 'undefined' || config.settings.api_auth_token === ''){
        res.status(400).json({ result: false, errors: ['Not allowed'] });
        return;
    }

    // The API schema
    let articleSchema = {
        'type': 'object',
github Casa / Casa-Node-Manager / utils / settingsSchema.js View on Github external
function validateSparseSettingsSchema(data) { // eslint-disable-line id-length

  // json schema cannot handle special characters like emojis. Here we handle length errors.
  if (data.lnd.lndNodeAlias) {
    try {
      utilValidator.isValidAliasLength(data.lnd.lndNodeAlias);
    } catch (error) {
      const response = ALIAS_TOO_LONG_ERROR;
      response.errors[0].instance = data.lnd.lndNodeAlias;

      return response;
    }
  }

  // handle all other errors
  var validator = new Validator();
  validator.addSchema(availableNetworks);
  validator.addSchema(sparseLndSchema);
  validator.addSchema(sparseBitcoindSchema);
  validator.addSchema(availableUnits);
  validator.addSchema(sparseSystemSchema);

  return validator.validate(data, sparseSettingsSchema);
}
github apigee / apigeelint / test / specs / testdistributedQuotaCheck.js View on Github external
it("should create a report object with valid schema", function() {
        var schema = require("./../fixtures/reportSchema.js"),
          Validator = require("jsonschema").Validator,
          v = new Validator(),
          validationResult,
          jsonReport;

        var jsonReport = JSON.parse(jsimpl(bundle.getReport()));
        validationResult = v.validate(jsonReport, schema);
        assert.equal(
          validationResult.errors.length,
          0,
          validationResult.errors
        );
      });
    }
github creativemarket / csxs / src / tasks / config.js View on Github external
* http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 *
 * @author Brian Reavis 
 */

var fs         = require('fs');
var path       = require('path');
var jsmin      = require('jsmin').jsmin;
var jsonschema = require('jsonschema');
var schema     = require('../../schema.json');
var validator  = new jsonschema.Validator();

if (schema.definitions) {
	for (var key in schema.definitions) {
		if (schema.definitions.hasOwnProperty(key)) {
			validator.addSchema(schema.definitions[key], '/definitions/' + key);
		}
	}
}

delete schema.definitions;

roto.defineTask('csxs.config_load', function(callback, options, target, globalOptions){
	var path_config = globalOptions.config || 'csxs.json';

	/**
	 * Reads and parses "csxs.json".
github dharmaprotocol / dharma.js / dist / lib / src / schemas / schema_validator.js View on Github external
function SchemaValidator() {
        this._validator = new jsonschema_1.Validator();
        for (var _i = 0, _a = values(schemas_1.Schemas); _i < _a.length; _i++) {
            var schema = _a[_i];
            this._validator.addSchema(schema, schema.id);
        }
    }
    SchemaValidator.prototype.addSchema = function (schema) {
github replicatedhq / kots / api / src / watch / resolvers / watch_mutations.ts View on Github external
function validateJson(json, checkedSchema) {
  try {
    JSON.parse(json);
  } catch (err) {
    logger.info({msg: "JSON is not valid", err});
    throw new ReplicatedError("JSON is not valid");
  }

  const v = new Validator();
  const validationResult = v.validate(JSON.parse(json), schema);

  if (!validationResult.valid) {
    const resultErrors = validationResult.errors;
    const err = resultErrors.map(e => e.message)[0];
    const upperCaseErr = err.charAt(0).toUpperCase() + err.substr(1);
    throw new ReplicatedError(upperCaseErr);
  }
}
github ng-vcl / ng-vcl / jss-form.component.js View on Github external
return function (c) {
            if (!VALIDATOR) {
                VALIDATOR = new Validator();
            }
            var result = VALIDATOR.validate(c.value, schema, {});
            if (result && !result.valid) {
                var error_1 = {};
                result.errors.forEach(function (err) {
                    var key = prefix ? err.property + '.' + err.name : err.name;
                    error_1[key] = err.message;
                });
                return error_1;
            }
            return null;
        };
    };