/* Schema Object Validators
4756
function validateArrayTypeItemsExistence (api, response, schema, path) {
  if (schema.type === 'array' && _.isUndefined(schema.items)) {
    response.errors.push({
      code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
      message: 'Missing required property: items',
      path: path
    });
  }
}
1198515
public void validate(String path, Schema schema, Object value, List<ValidationResult> results) {
		String name = path != null ? path : "value";
		Object value1 = ObjectReader.getProperty(value, _property1);
		Object value2 = ObjectReader.getProperty(value, _property2);

		if (!ObjectComparator.compare(value1, _operation, value2)) {
			results.add(new ValidationResult(path, ValidationResultType.Error, "PROPERTIES_NOT_MATCH",
					name + " must have " + _property1 + " " + _operation + " " + _property2, value2, value1));
		}
	}
144605
function isRequired(schema) {
    var required = false;
    if (schema[SCHEMAREQUIRED]) {
      try {
        required = schema[SCHEMAREQUIRED];
        if (typeof required != "boolean") {
          throw new ValidationException(
            schema[SCHEMAREQUIRED] + " cast exception."
          );
        }
      } catch (e) {
        throw new ValidationException(
          schema[SCHEMAREQUIRED] + " cast exception."
        );
      }
    }
    return required;
  }
705332
protected function validateSchema()
    {
        $schemaPath = $this->getOption('schemaPath');

        if ($schemaPath === null) {
            return;
        }

        $schemaData = json_decode(file_get_contents($schemaPath));

        if (!class_exists('\\JsonSchema\\Validator')) {
            throw new \RuntimeException(
                'If you want to validate a JSON schema, you must require package "justinrainbow/json-schema"-'
            );
        }

        $validator = new \JsonSchema\Validator();
        $validator->check($this->getContents(), $schemaData);

        if (!$validator->isValid()) {
            $errors = [];

            foreach ((array) $validator->getErrors() as $error) {
                $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message'];
            }

            throw DecodeException::create($this->getPath(), ['errors' => $errors]);
        }
    }
493783
function validate(entityAspect, validator, value, context) {
    var ve = validator.validate(value, context);
    if (ve) {
      entityAspect._addValidationError(ve);
      return false;
    } else {
      var key = ValidationError.getKey(validator, context ? context.propertyName : null);
      entityAspect._removeValidationError(key);
      return true;
    }
  }
1309413
function Validator(config) {
  
  // Instance properties
  this.rules = {};
  this.rulesCount = 0;
  this.messages = {};
  this.optional = [];
  this.filters = {};
  this.postFilters = {};
  this.postValidations = [];
  
  // Options
  this.config = protos.extend({
    cleanup: true
  }, config || {});
  
  // Set context
  Object.defineProperty(this, '__context', {
    value: {},
    writable: true,
    enumerable: false,
    configurable: false
  });

  // App property
  Object.defineProperty(this, 'app', {
    value: protos.app,
    writable: true,
    enumerable: false,
    configurable: false
  });
  
}
1254939
def valid(self, instance, schema):
        """"""
        try:
            jsonschema.validate(instance, schema)
        except jsonschema.exceptions.ValidationError as ex:
            self.stderr.write("    VALIDATION ERROR: {}".format(instance['name'] if 'name' in instance else ''))
            self.stderr.write("        path:       {}".format(ex.path))
            self.stderr.write("        message:    {}".format(ex.message))
            self.stderr.write("        validator:  {}".format(ex.validator))
            self.stderr.write("        val. value: {}".format(ex.validator_value))
            return False

        try:
            # Check that default values fit field schema.
            for field in ['input', 'output', 'schema']:
                for schema, _, path in iterate_schema({}, instance.get(field, {})):
                    if 'default' in schema:
                        validate_schema({schema['name']: schema['default']}, [schema])
        except ValidationError:
            self.stderr.write("    VALIDATION ERROR: {}".format(instance['name']))
            self.stderr.write("        Default value of field '{}' is not valid.". format(path))
            return False

        return True
944259
function processXsd() {
	console.log();
	console.log('Processing XML schema...');
	var src = x2j.xml2json(xsdStr,{"attributePrefix": "@","valueProperty": false, "coerceTypes": false});
	var obj = xsd.getJsonSchema(src,'nitro-schema','',true);

	console.log('Validating generated JSON schema...');
	var validate = ajv.compile(jsonSchema);
	validate(obj);
	var errors = validate.errors;
	if (errors) {
		console.log(errors);
		return false;
	}
	else {
		fs.writeFileSync('./nitroApi/nitro-schema.yaml',yaml.safeDump(obj),'utf8');

		var existing = openapi.components.schemas;
		var root = obj.properties;
		openapi.components.schemas = obj.definitions;
		openapi.components.schemas.nitro = root.nitro;
		openapi.components.schemas.nitro.additionalProperties = true; // cope with undefined 'items'
		openapi.components.schemas.ErrorModel = existing.ErrorModel;
		recurse(openapi.components.schemas,{},function(obj,key,state){
			if ((key === '$ref') && (typeof obj.$ref === 'string') && (obj.$ref.startsWith('#/definitions/'))) {
				obj.$ref = obj.$ref.replace('#/definitions/','#/components/schemas/');
			}
		});

		return true;
	}
}
150117
def _validate(self, inst: "InstanceNode", scope: ValidationScope,
                  ctype: ContentType) -> None:
        """"""
        if scope.value & ValidationScope.syntax.value:   # schema
            self._check_schema_pattern(inst, ctype)
        for m in inst:
            inst._member(m).validate(scope, ctype)
        super()._validate(inst, scope, ctype)
964042
function validateArray(node, schema, key) {
    if (Array.isArray(node)) {
      if (schema[SCHEMALENGTH]) {
        checkLength(node.length, schema, key);
      }
      for (var arrayI = 0; arrayI < node.length; arrayI++) {
        try {
          validateNode(node[arrayI], schema[SCHEMADATA], "");
        } catch (e) {
          throw new ValidationException(
            e.message + key + " position " + arrayI
          );
        }
      }
    } else {
      throw new ValidationException("Expected array for " + key);
    }
  }
176761
function generateValidationFn(schema) {
        return function (req) {

            // if already an error, return without doing any additional validation
            if (req.error) { return req; }

            var keys = Object.keys(schema);
            var len = (req.value && req.value.trim().length) || 0;
            var i, key, originalKey;

            for (i = 0; i < keys.length; i++) {
                key = originalKey = keys[i];
                if (key.indexOf('ui-') === 0) {
                    key = key.substring(3);
                }

                // if validation function exists but it returns false then we have error
                if (check[key] && !check[key](schema, req.value)) {
                    var errMsg = schema[key + 'Desc'] || errorMessage[key] || 'Invalid input';
                    req.error = errMsg
                        .replace('{' + key + '}', schema[originalKey])
                        .replace('{value}', req.value)
                        .replace('{length}', len);
                    break;
                }
            }

            return req;
        };
    }
684058
function documentFactory(validators) {
    function documentValidator(doc, attr, debug) {
      doc = doc || {};
      attr = attr || {};
      
      var errors = [];

      _.each(validators, function (valset, field) {
        var err = null;
        var value = doc[field];

        // turn validators into an array if it isn't one
        valset = _.arrayify(valset);

        // run all the validation for this field
        _.each(valset, function (validator) {

          // if there's already an error, don't bother
          if (err) return;
          err = validator(value, attr, (field == 'badge'));

        });

        // set the correct field on the error
        if (err) err.field = field;

        // jam it into the array with the rest of 'em
        errors.push(err);
      });

      // throw out any undefined or nulls that snuck in there
      errors = _.reject(errors, _.isMissing);

      if (errors.length) {
        return { name: 'doc', errors: errors };
      }
    }
    documentValidator.meta = { name : 'doc' };
    return documentValidator;
  }
1106652
function validate(doc, schema, prefix, options) {
  schema.validate(doc, prefix, options);
}
742882
private void validate(Source src, Result res) throws XMLStreamException {
        try {
            Validator v = schemaFactory.newSchema().newValidator();
            v.setResourceResolver(schemaFactory.getResourceResolver());
            v.validate(src, res);
        } catch (SAXException | IOException e) {
            throw new XMLStreamException(e);
        }
    }
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
  }
}
334397
function validateArgs (args, methodMeta) {
    // do not validate if no schema
    if (!defined(methodMeta.schema.args)) {
        return args
    }
    // do not validate if disabled
    if (!methodMeta.validateArgs) {
        return args
    }
    // get validator
    var ajv = methodMeta.ajv
    // throw error if validation fails
    if (!ajv.validate(methodMeta.schema.args.id, args)) {
        // create error
        var error = new Error(`${methodMeta.signature}: invalid args - ${ajv.errorsText()}`)
        // add ajv errors to error data
        error.data = ajv.errors
        // throw error
        throw error
    }
    // return possibly modified args
    return args
}
953495
public function validate(
        Schema $schema,
        $value,
        $forceNoAdditionalProperties = false,
        $requireAllWhenNotSpecified = false
    ): ValidationResult {

        $definition = $schema->getDefinition();

        if ($requireAllWhenNotSpecified || $forceNoAdditionalProperties) {
            $hackDefinition = function (\stdClass $definition) use (
                $forceNoAdditionalProperties,
                $requireAllWhenNotSpecified,
                &$hackDefinition
            ) {
                if (isset($definition->properties)) {
                    if ($forceNoAdditionalProperties) {
                        $definition->additionalProperties = false;
                    }
                    if ($requireAllWhenNotSpecified && !isset($definition->required)) {
                        $definition->required = array_keys((array)$definition->properties);
                    }
                }

                foreach ($definition as $item) {
                    if ($item instanceof \stdClass) {
                        $hackDefinition($item);
                    }
                }
            };
            $hackDefinition($definition = clone $definition);
        }

        return $this->getResult($definition, $value);
    }