Creates a validation schema for the constraints of the specified type
352360
function makeTypeConstraintsSchema(typeName) {
  const allTypeConstraints = typeSpecificConstraintSchemas();
  const constraints = Object.assign({ }, universalConstraintSchemas(typeEqualitySchemas[typeName]), allTypeConstraints[typeName]);

  return joi.object().keys(constraints)
    // Prevent the use of more than one constraint from the "required value" category
    .without('required', [ 'mustNotBeMissing', 'mustNotBeNull' ])
    .without('mustNotBeMissing', [ 'required', 'mustNotBeNull' ])
    .without('mustNotBeNull', [ 'required', 'mustNotBeMissing' ])

    // Prevent the use of more than one constraint from the "equality" category
    .without('mustEqual', [ 'mustEqualStrict', 'mustEqualIgnoreCase' ])
    .without('mustEqualStrict', [ 'mustEqual', 'mustEqualIgnoreCase' ])
    .without('mustEqualIgnoreCase', [ 'mustEqual', 'mustEqualStrict' ])

    // Prevent the use of more than one constraint from the "minimum value" category
    .without('minimumValue', [ 'minimumValueExclusive', 'mustEqual', 'mustEqualStrict', 'mustEqualIgnoreCase' ])
    .without('minimumValueExclusive', [ 'minimumValue', 'mustEqual', 'mustEqualStrict', 'mustEqualIgnoreCase' ])

    // Prevent the use of more than one constraint from the "maximum value" category
    .without('maximumValue', [ 'maximumValueExclusive', 'mustEqualStrict', 'mustEqual', 'mustEqualIgnoreCase' ])
    .without('maximumValueExclusive', [ 'maximumValue', 'mustEqualStrict', 'mustEqual', 'mustEqualIgnoreCase' ])

    // Prevent the use of more than one constraint from the "immutability" category
    .without('immutable', [ 'immutableStrict', 'immutableWhenSet', 'immutableWhenSetStrict' ])
    .without('immutableStrict', [ 'immutable', 'immutableWhenSet', 'immutableWhenSetStrict' ])
    .without('immutableWhenSet', [ 'immutable', 'immutableStrict', 'immutableWhenSetStrict' ])
    .without('immutableWhenSetStrict', [ 'immutable', 'immutableStrict', 'immutableWhenSet' ])

    // Prevent the use of more than one constraint from the "skip validation" category
    .without('skipValidationWhenValueUnchanged', [ 'skipValidationWhenValueUnchangedStrict' ]);
}
973522
def _validate_data(data, schema, validator_cls):
    
    validator = validator_cls(schema)
    _errors = defaultdict(list)
    for err in validator.iter_errors(data):
        path = err.schema_path

        # Code courtesy: Ruslan Karalkin
        # Looking in error schema path for
        # property that failed validation
        # Schema example:
        # {
        #    "type": "object",
        #    "properties": {
        #        "foo": {"type": "number"},
        #        "bar": {"type": "string"}
        #     }
        #    "required": ["foo", "bar"]
        # }
        #
        # Related err.schema_path examples:
        # ['required'],
        # ['properties', 'foo', 'type']

        if "properties" in path:
            path.remove("properties")
        key = path.popleft()

        # If validation failed by missing property,
        # then parse err.message to find property name
        # as it always first word enclosed in quotes
        if key == "required":
            key = err.message.split("'")[1]

        _errors[key].append(str(err))

    if _errors:
        _raise_exception(
            web.HTTPBadRequest,
            "Request is invalid; There are validation errors.",
            _errors)
1233059
void validate(Schema schema, ImmutableList<ProfileFileElement> profileFiles) {
    List<String> errors = new ArrayList<>();

    for (ProfileFileElement profileFile : profileFiles) {
      for (TypeConfigElement typeConfig : profileFile.getTypeConfigs()) {
        ProtoType type = importedType(ProtoType.get(typeConfig.getType()));
        if (type == null) continue;

        Type resolvedType = schema.getType(type);
        if (resolvedType == null) {
          errors.add(String.format("unable to resolve %s (%s)",
              type, typeConfig.getLocation()));
          continue;
        }

        String requiredImport = resolvedType.location().getPath();
        if (!profileFile.getImports().contains(requiredImport)) {
          errors.add(String.format("%s needs to import %s (%s)",
              typeConfig.getLocation().getPath(), requiredImport, typeConfig.getLocation()));
        }
      }
    }

    if (!errors.isEmpty()) {
      throw new SchemaException(errors);
    }
  }
816923
def validate(self, obj):
        """"""
        try:
            if self.resolver is not None:
                jsonschema.validate(obj, self.schema, resolver=self.resolver)
            else:
                jsonschema.validate(obj, self.schema)
        except jsonschema.ValidationError as exc:
            raise exceptions.ValidationError(str(exc))
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;
        };
    }
423936
private void validateRelationType(RelationType relationType) {
        ValidateGlobalRules.validateHasMinimumRoles(relationType).ifPresent(errorsFound::add);
        errorsFound.addAll(ValidateGlobalRules.validateRelationTypesToRolesSchema(relationType));
    }
966067
function generateConfigsFromSchema(schema) {
    const configSet = new RuleConfigSet();

    if (Array.isArray(schema)) {
        for (const opt of schema) {
            if (opt.enum) {
                configSet.addEnums(opt.enum);
            } else if (opt.type && opt.type === "object") {
                if (!configSet.addObject(opt)) {
                    break;
                }

            // TODO (IanVS): support oneOf
            } else {

                // If we don't know how to fill in this option, don't fill in any of the following options.
                break;
            }
        }
    }
    configSet.addErrorSeverity();
    return configSet.ruleConfigs;
}
1162807
function partial(schema, defaults, options) {
  if (kindOf(schema) !== 'object') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Partial structs must be defined as an object, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const obj = scalar('object', undefined, options)
  const ks = []
  const properties = {}

  for (const key in schema) {
    ks.push(key)
    const s = schema[key]
    const kind = any(s, undefined, options)
    properties[key] = kind
  }

  const name = 'partial'
  const type = `{${ks.join()},...}`
  const validate = (value = resolveDefaults(defaults)) => {
    const [error] = obj.validate(value)

    if (error) {
      error.type = type
      return [error]
    }

    const errors = []
    const ret = {}

    for (const key in properties) {
      let v = value[key]
      const kind = properties[key]

      if (v === undefined) {
        const d = defaults && defaults[key]
        v = resolveDefaults(d, value)
      }

      const [e, r] = kind.validate(v, value)

      if (e) {
        const allE = e.errors || [e]
        allE.forEach(singleE => {
          singleE.path = [key].concat(singleE.path)
          singleE.data = value
          errors.push(singleE)
        })
        continue
      }

      if (key in value || r !== undefined) {
        ret[key] = r
      }
    }

    if (errors.length) {
      const first = errors[0]
      first.errors = errors
      return [first]
    }

    return [undefined, ret]
  }

  return new Kind(name, type, validate)
}
88093
@SuppressWarnings("unchecked")
    public Constraint getConstraint(String ... typeInfo) {
        if( typeInfo == null || typeInfo.length < 1 ) {
            return getConstraints().iterator().next();
        }
        else if( typeInfo.length == 1 ) {
            Constraint c = getConstraint(new String[0]);
            DataType<?> attr = c.getType();
            Boolean b;
            
            b = (Boolean)attr.getValue(typeInfo[0]);
            if( b == null || !b ) {
                return constraints.get(1);
            }
            else {
                return constraints.get(2);
            }
        }
        else {
            return super.getConstraint(typeInfo);
        }
    }
404042
def schema():
        """"""
        return Schema({
            'script': And(Or(type(' '), type(u' ')), len),
            Optional('title', default=''): str,
            Optional('model', default={}): {Optional(And(str, len)): object},
            Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
            Optional('item', default=None): object,
            Optional('dry_run', default=False): bool,
            Optional('debug', default=False): bool,
            Optional('strict', default=False): bool,
            Optional('variables', default={}): {
                Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
                    Or(type(' '), type(u' '))
            },
            Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
            Optional('internal', default=False): bool
        })
1295022
public Map<String, Map<String, Map<String, Map<String, ?>>>> validationConstraints() {
		return getEntity(invokeGet("_constraints", null), Map.class);
	}
1066033
def validate(text, file, schema_type):
    """"""
    content = None

    if text:
        print('Validating text input...')
        content = text

    if file:
        print('Validating file input...')
        content = file.read()

    if content is None:
        click.secho('Please give either text input or a file path. See help for more details.', fg='red')
        exit(1)

    try:
        if schema_type == 'dependencies':
            validator = DependenciesSchemaValidator()
        elif schema_type == 'actions':
            validator = ActionsSchemaValidator()
        else:
            raise Exception('Unknown type')

        validator.validate_json(content)
        click.secho('Valid JSON schema!', fg='green')
    except Exception as e:
        click.secho('Invalid JSON schema!', fg='red')
        raise e
1160999
def assert_valid_schema(schema: GraphQLSchema) -> None:
    
    errors = validate_schema(schema)
    if errors:
        raise TypeError("\n\n".join(error.message for error in errors))
1254281
function Validation(schema, custom) {
		Inspection.prototype.constructor.call(this, schema, _merge(Validation.custom, custom));
		var _error = [];

		this._basicFields = Object.keys(_validationAttribut);
		this._customFields = Object.keys(this._custom);
		this.origin = null;

		this.report = function (message, code, reason) {
			var newErr = {
				code: code || this.userCode || null,
				reason: reason || 'unknown',
				message: this.userError || message || 'is invalid',
				property: this.userAlias ? (this.userAlias + ' (' + this._dumpStack() + ')') : this._dumpStack()
			};
			_error.push(newErr);
			return this;
		};

		this.result = function () {
			return {
				error: _error,
				valid: _error.length === 0,
				format: function () {
					if (this.valid === true) {
						return 'Candidate is valid';
					}
					return this.error.map(function (i) {
						return 'Property ' + i.property + ': ' + i.message;
					}).join('\n');
				}
			};
		};
	}
900389
function (typeName, fieldName, value) {

              var validResult = { valid: true },
                typeConstraints = constraintsForType(typeName);

              if (valdrUtil.has(typeConstraints, fieldName)) {
                var fieldConstraints = typeConstraints[fieldName],
                  fieldIsValid = true,
                  validationResults = [],
                  violations = [];

                angular.forEach(fieldConstraints, function (constraint, validatorName) {
                  var validator = validators[validatorName];

                  if (angular.isUndefined(validator)) {
                    $log.warn('No validator defined for \'' + validatorName +
                      '\'. Can not validate field \'' + fieldName + '\'');
                    return validResult;
                  }

                  var valid = validator.validate(value, constraint);
                  var validationResult = {
                    valid: valid,
                    value: value,
                    field: fieldName,
                    type: typeName,
                    validator: validatorName
                  };
                  angular.extend(validationResult, constraint);

                  validationResults.push(validationResult);
                  if (!valid) {
                    violations.push(validationResult);
                  }
                  fieldIsValid = fieldIsValid && valid;
                });

                return {
                  valid: fieldIsValid,
                  violations: violations.length === 0 ? undefined : violations,
                  validationResults: validationResults.length === 0 ? undefined : validationResults
                };
              } else {
                return validResult;
              }
            }
57025
function validator (data, schema) {
  const result = Object.assign({}, data)
  Object.keys(schema).map(key => {
    let value = schema[key]
    const type = typeof value
    if (type !== 'object') {
      value = {
        transform: value
      }
    }
    validate(value, result, key)
  })
  return result
}
979839
public Map<String, Map<String, Map<String, Map<String, ?>>>> getAllValidationConstraints(String... types) {
		Map<String, Map<String, Map<String, Map<String, ?>>>> allConstr = new LinkedHashMap<>();
		if (types == null || types.length == 0) {
			types = ParaObjectUtils.getAllTypes(this).values().toArray(new String[0]);
		}
		try {
			for (String aType : types) {
				Map<String, Map<String, Map<String, ?>>> vc = new LinkedHashMap<>();
				// add all core constraints first
				if (ValidationUtils.getCoreValidationConstraints().containsKey(aType)) {
					vc.putAll(ValidationUtils.getCoreValidationConstraints().get(aType));
				}
				// also add the ones that are defined locally for this app
				Map<String, Map<String, Map<String, ?>>> appConstraints = getValidationConstraints().get(aType);
				if (appConstraints != null && !appConstraints.isEmpty()) {
					vc.putAll(appConstraints);
				}
				if (!vc.isEmpty()) {
					allConstr.put(aType, vc);
				}
			}
		} catch (Exception ex) {
			logger.error(null, ex);
		}
		return allConstr;
	}