Validates data based on Joi schemas

@param {Object} data the data to be validated
@param {Object} schema the object schema specified in Joi against which data is validated
2097
function validate (data, schema) {
  if (!data || !schema) {
    throw new Error('Trying to validate without passing data and schema')
  }
  return Joi.validate(data, schema)
}
994654
def _validated(self, data):
        """"""
        for sub in self.schemas:
            data = sub(data)
        return data
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)
156385
function validate(key) {
        var type = getType(key);
        if (type === "array") {
            for (var i = 0; i < key.length; i++) {
                validate(key[i]);
            }
        }
        else if (!types[type] || (type !== "string" && isNaN(key))) {
            throw idbModules.util.createDOMException("DataError", "Not a valid key");
        }
    }
408607
function assertion(value, schema, message, vars, ssf) {
	return Joi.validate(value, schema, function(err, value) {
		// fast way
		if (!err) {
			return value;
		}

		// assemble message
		var msg = '';

		// process message (if any)
		var mtype = typeof message;
		if (mtype === 'string') {
			if (vars && typeof vars === 'object') {
				// mini template
				message = message.replace(/\{([\w]+)\}/gi, function (match, key) {
					if (hasOwnProp.call(vars, key)) {
						return vars[key];
					}
				});
			}
			msg += message + ': ';
		}

		// append schema label
		msg += getLabel(schema.describe(), err);

		// append some of the errors
		var maxDetails = 4;

		msg += err.details.slice(0, maxDetails).map(function(det) {
			if (/^\w+\.\w/.test(det.path)) {
				return '[' + det.path + '] ' + det.message;
			}
			return det.message;
		}).join(', ');

		if (err.details.length > maxDetails) {
			var hidden = (err.details.length - maxDetails);
			msg += '... (showing ' + (err.details.length - hidden) + ' of ' + err.details.length + ')';
		}

		// booya
		throw new AssertionError(msg, {
			details: err.details,
			value: value
		}, ssf);
	});
}
367163
def validate(self, data, schema, **kwargs):
        """"""
        if not isinstance(schema, dict):
            schema = {'$ref': schema}
        return validate(
            data,
            schema,
            resolver=self.ref_resolver_cls.from_schema(schema),
            types=self.app.config.get('RECORDS_VALIDATION_TYPES', {}),
            **kwargs
        )
263894
function validateRequiredPropertiesExist (schema, schemaId) {
  /**
   * Recursively collects all properties of the schema and its ancestors. They are added to the props object.
   */
  function collectProperties (schemaObj, props) {
    if (schemaObj.properties) {
      for (var property in schemaObj.properties) {
        if (schemaObj.properties.hasOwnProperty(property)) {
          props[property] = schemaObj.properties[property];
        }
      }
    }
    if (schemaObj.allOf) {
      schemaObj.allOf.forEach(function (parent) {
        collectProperties(parent, props);
      });
    }
  }

  if (schema.required && Array.isArray(schema.required)) {
    var props = {};
    collectProperties(schema, props);
    schema.required.forEach(function (requiredProperty) {
      if (!props[requiredProperty]) {
        throw ono.syntax("Validation failed. Property '%s' listed as required but does not exist in '%s'",
          requiredProperty, schemaId);
      }
    });
  }
}
1336639
private function validateNode($node, CustomArrayObject $schema, $element = [])
    {
        $nodeSchema = new CustomArrayObject($schema[$node]);

        foreach ($nodeSchema->getArrayKeys() as $key) {
            $this->currentNode = $node . '.' . $key;
            $this->getLogger()->info("We are in element: {$this->currentNode}");

            $nodeData = isset($element[$key]) ? $element[$key] : null;


            $this->validateTypeFieldIsPresent($nodeSchema[$key]);

            $validator = $this->getClassValidator($nodeSchema[$key]);
            $validator->setParams($this->params);

            $isRequired = $this->requiredMode ? $validator->isRequired() : false;

            if ($isRequired === false && empty($nodeData)) {
                $this->getLogger()->info("Element: {$this->currentNode} has empty non-required data. We skip other check");
                continue;
            }

            $this->validateRequiredFieldIsPresent($nodeData);

            $this->validateExcessiveKeys($validator, new CustomArrayObject($nodeSchema[$key]), $nodeData);

            $this->validateNodeValue($validator, $nodeData);

            $this->validateNesting($validator, $nodeData);

            if ($validator->isNested()) {
                $this->getLogger()->info("Element: {$this->currentNode} has children");

                foreach ($nodeData as $record) {
                    $this->validateNode($key, $nodeSchema, $record);
                }
            } else {
                $this->validateNode($key, $nodeSchema, $nodeData);
            }

            $this->getLogger()->info("Element: {$this->currentNode} finished checking successfully.");
        }
    }
830170
function middleware(schema, options = optionsDefault) {
    return (req, res, next) => {
        // Test if schema exists
        /* istanbul ignore if */
        if (!schema) {
            next();
        }

        // Test if Joi is provided
        const Joi = options.joi || require('joi');

        // Object to validate
        const objectToValidate = {};
        ['params', 'body', 'query', 'headers'].forEach((key) => {
            if (schema[key]) {
                objectToValidate[key] = req[key];
            }
        });

        // Get joi options
        const joiOptions = options.joiOptions || {};

        // Get callback
        const callback = options.validationCallback || validationCallback;

        return Joi.validate(objectToValidate, schema, joiOptions, callback(req, res, next, options));
    };
}
705463
function validate (schema, data, key) {
  let value = data[key]
  const bool = value == null || value === ''
  const { required, type, validate, transform, elements } = schema
  const def = schema['default']
  // trigger error if undefined but required
  if (required && bool) throw new Error(`field ${key} is missing`)
  // coerce to type
  if (type && !bool) {
    let before = coerce(type, key, value)
    data[key] = elements
      ? (type === 'object' ? validator(before, elements) : before.map(item => validator(item, elements)))
      : before
  }
  // validate value
  if (validate) {
    const cb = check(validate, key)
    if (type === 'array') value.map(cb)
    else cb(value)
  }
  // apply default value
  if (def && bool) data[key] = def
  // apply transform
  if (transform && def == null) {
    data[key] = typeof transform === 'function'
      ? (type === 'array' ? value.map(transform) : transform(value))
      : transform
  }
}
761262
function JsonSchema (schema) {
  if (!schema) {
    throw ono({ status: 500 }, "Missing JSON schema");
  }
  if (schema.type !== undefined && dataTypes.indexOf(schema.type) === -1) {
    throw ono({ status: 500 }, "Invalid JSON schema type: %s", schema.type);
  }

  this.schema = schema;
}
148705
def validate(data)
      JSON::Validator.validate!(self, data)
    rescue JSON::Schema::ValidationError => e
      raise DataPackage::ValidationError.new(e.message)
    end
40518
function tv4_validateSchema(schema) {
        var is_draft_schema = (schema.id === exports.DRAFT_SCHEMA_ID);
        var draft_schema = (is_draft_schema) ? schema : tv4.getSchema(exports.DRAFT_SCHEMA_ID);
        var report = tv4.validateMultiple(schema, draft_schema);
        return report;
    }
35951
function validate(options) {
    const schema = joi.object().keys({
        config: joi.array().min(_.keys(options.models).length).required(),
        acl: joi.object().required(),
        models: joi.object().required()
    });
    joi.assert(options, schema, 'Invalid Shield Options:');
    return true;
}
276613
def validate(schema):
    """"""
    try:
        tableschema.validate(schema)
        click.echo("Schema is valid")
        sys.exit(0)
    except tableschema.exceptions.ValidationError as exception:
        click.echo("Schema is not valid")
        click.echo(exception.errors)
        sys.exit(1)
599477
function validate(candidate) {
  if (candidate.doc_type) {
    var schema = schemasDeepCopy()[candidate.doc_type];
    validator.validate(candidate, schema);
    var errors = validator.getLastErrors();
    return errors;
  }

  return [{
    dataModel: 'the object to be validated is missing a `doc_type` property'
  }];
}
1106652
function validate(doc, schema, prefix, options) {
  schema.validate(doc, prefix, options);
}