factory method for creating validator instances
347329
public FormFieldValidator createValidator(Element constraint, BpmnParse bpmnParse, ExpressionManager expressionManager) {

    String name = constraint.attribute("name");
    String config = constraint.attribute("config");

    if("validator".equals(name)) {

      // custom validators

      if(config == null || config.isEmpty()) {
        bpmnParse.addError("validator configuration needs to provide either a fully " +
        		"qualified classname or an expression resolving to a custom FormFieldValidator implementation.",
        		constraint);

      } else {
        if(StringUtil.isExpression(config)) {
          // expression
          Expression validatorExpression = expressionManager.createExpression(config);
          return new DelegateFormFieldValidator(validatorExpression);
        } else {
          // classname
          return new DelegateFormFieldValidator(config);
        }
      }

    } else {

      // built-in validators

      Class<? extends FormFieldValidator> validator = validators.get(name);
      if(validator != null) {
        FormFieldValidator validatorInstance = createValidatorInstance(validator);
        return validatorInstance;

      } else {
        bpmnParse.addError("Cannot find validator implementation for name '"+name+"'.", constraint);

      }

    }

    return null;


  }
698168
function validate () {
    var this$1 = this;
    var args = [], len = arguments.length;
    while ( len-- ) args[ len ] = arguments[ len ];

    var validators;
    var value;
    var cb;
    var ret = true;

    if (args.length === 3) {
      validators = [args[0]];
      value = args[1];
      cb = args[2];
    } else if (args.length === 2) {
      if (isPlainObject(args[0])) {
        validators = [args[0].validator];
        value = args[0].value || this.getValue();
        cb = args[1];
      } else {
        validators = this._keysCached(this._uid.toString(), this.results);
        value = args[0];
        cb = args[1];
      }
    } else if (args.length === 1) {
      validators = this._keysCached(this._uid.toString(), this.results);
      value = this.getValue();
      cb = args[0];
    } else {
      validators = this._keysCached(this._uid.toString(), this.results);
      value = this.getValue();
      cb = null;
    }

    if (args.length === 3 || (args.length === 2 && isPlainObject(args[0]))) {
      ret = this._validate(validators[0], value, cb);
    } else {
      validators.forEach(function (validator) {
        ret = this$1._validate(validator, value, cb);
      });
    }

    return ret
  }
964832
function Validator(opts) {
	this.opts = {
		messages: deepExtend({}, defaultMessages)
	};

	if (opts)
		deepExtend(this.opts, opts);

	this.messages = this.opts.messages;
	this.messageKeys = Object.keys(this.messages);

	// Load rules
	this.rules = loadRules();
	this.cache = new Map();
}
584913
def _factory(cls, constraints, op):
        
        pieces = []
        for i, constraint in enumerate(constraints):
            pieces.append(constraint)
            if i != len(constraints) - 1:
                pieces.append(op)
        return cls(pieces)
989824
def _verify_validator(self, validator, path):
        """"""

        # Validator should be a function
        if not callable(validator):
            raise SchemaFormatException("Invalid validations for {}", path)

        # Validator should accept a single argument
        (args, varargs, keywords, defaults) = getargspec(validator)
        if len(args) != 1:
            raise SchemaFormatException("Invalid validations for {}", path)
1334542
def validate(cls, partial=True, **kwargs):
        
        data = kwargs
        if not partial:
            data = dict(**kwargs, **{col.name: None for col in cls.__table__.c
                                     if col.name not in kwargs})

        errors = defaultdict(list)
        for name, value in data.items():
            for validator in cls._get_validators(name):
                try:
                    validator(value)
                except ValidationError as e:
                    e.model = cls
                    e.column = name
                    errors[name].append(str(e))

        if errors:
            raise ValidationErrors(errors)
692517
private ValidatorFactory getValidatorFactory() {
        if (!ValidationMode.NONE.equals(validationMode)) {
            try {
                return Validation.buildDefaultValidatorFactory();
            } catch (ValidationException e) {
                LOGGER.debug("No JSR 303 Bean Validation provider available.", e);
            }
        }
        return null;
    }
1179629
def add_validator(self, validator):
        
        if not isinstance(validator, AbstractValidator):
            err = 'Validator must be of type {}'.format(AbstractValidator)
            raise InvalidValidator(err)

        self.validators.append(validator)
        return self
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;
  }
449810
function addValidator(name, validator, params) {
    var _this = this;
    var validators = validator instanceof Array ? validator : [validator];
    var validate = void 0;

    if (typeof validator === 'string') {
        validate = function validate() /*value, arg, options*/{
            return _this[validator].apply({ alias: name, _this: _this }, arguments);
        };
    } else {
        validate = function validate(value /*arg, options*/) {
            var args = Array.prototype.slice.call(arguments, 2);
            var arg1 = arguments[1];
            var arg2 = arguments[2];
            var _this2 = this && this._this || _this;
            var isSimpleArgsFormat = _this2[name][SIMPLE_ARGS_FORMAT] || _this2[SIMPLE_ARGS_FORMAT];
            var isOneOptionsArg = _this2[name][ONE_OPTIONS_ARG] || _this2[ONE_OPTIONS_ARG];
            var options = !isOneOptionsArg && isPlainObject(arg2) ? arg2 : {};

            if (arg1 != null && typeof arg1 !== 'boolean') {
                if (isPlainObject(arg1)) {
                    options = arg1;
                } else {
                    options[_this2[name][ARG] || _this2[ARG]] = arg1;

                    if (!isSimpleArgsFormat) {
                        args.shift();
                    }
                }
            }

            for (var i = 0; i < validators.length; i++) {
                var base = validators[i];

                switch (typeof base === 'undefined' ? 'undefined' : _typeof(base)) {
                    case 'function':
                        validator = validatorWrapper(_this2, name, base);break;

                    case 'string':
                        validator = _this2[base];break;

                    case 'object':
                        validator = _this2[base[0]];
                        options = assign({}, options, base[1]);
                }

                var error = validator.apply(this, [value, options].concat(args));

                if (error) {
                    return error;
                }
            }
        };
    }

    assign(validate, params);

    validate.curry = function () /*arg, options*/{
        var _arguments = arguments;
        //Partial application
        return function (value) {
            return validate.apply(_this, [value].concat(Array.prototype.slice.call(_arguments)));
        };
    };

    _this[name] = validate;
}
82568
function(attrs, options) {
    var validationErrors = BaseModel.__super__.validate.apply(this, arguments);
    if (validationErrors) return new ValidationError({
      errors: validationErrors
    });
  }
176218
protected function getValidatorInstance(): Validator
    {
        $factory = $this->container->make(ValidationFactory::class);

        if (method_exists($this, 'validator')) {
            $validator = $this->container->call([$this, 'validator'], compact('factory'));
        } else {
            $validator = $this->createDefaultValidator($factory);
        }

        if (method_exists($this, 'withValidator')) {
            $this->withValidator($validator);
        }

        return $validator;
    }
700077
function makeValidator(spec) {
  const props = 'header query params body'.split(' ');

  return async function validator(ctx, next) {
    if (!spec.validate) return await next();

    let err;

    for (let i = 0; i < props.length; ++i) {
      const prop = props[i];

      if (spec.validate[prop]) {
        err = validateInput(prop, ctx, spec.validate);

        if (err) {
          captureError(ctx, prop, err);
          if (!spec.validate.continueOnError) return ctx.throw(err);
        }
      }
    }

    await next();

    if (spec.validate._outputValidator) {
      debug('validating output');

      err = spec.validate._outputValidator.validate(ctx);
      if (err) {
        err.status = 500;
        return ctx.throw(err);
      }
    }
  };
}
342513
def __dump_validators(self):
        """"""
        if hasattr(self, '_validators'):
            validators_json = []
            for validator in self._validators:
                if isinstance(validator, PropertyValidator):
                    validators_json.append(validator.as_json())
                else:
                    raise APIError("validator is not a PropertyValidator: '{}'".format(validator))
            if self._options.get('validators', list()) == validators_json:
                # no change
                pass
            else:
                new_options = self._options.copy()  # make a copy
                new_options.update({'validators': validators_json})
                validate(new_options, options_json_schema)
                self._options = new_options
1184867
function validatorWrapper(validators, name, validator) {
    return function (value, options) {
        var error = void 0,
            args = arguments;
        var alias = this && this.alias;
        var validatorObj = validators[name];
        var validatorAliasObj = alias ? validators[alias] : {};
        var arg = validatorObj[ARG] || validatorAliasObj[ARG] || validators[ARG];
        var isSimpleArgsFormat = validatorObj[SIMPLE_ARGS_FORMAT] || validatorAliasObj[SIMPLE_ARGS_FORMAT] || validators[SIMPLE_ARGS_FORMAT];

        options = assign({}, validatorObj.defaultOptions, validatorAliasObj.defaultOptions, options);

        if (typeof options.parse === 'function') {
            value = options.parse(value);
        }

        if (options.hasOwnProperty(arg) && !isSimpleArgsFormat) {
            args = [value, options[arg]].concat(Array.prototype.slice.call(arguments, 1));
        }

        try {
            var resultHandler = validatorObj[RESULT_HANDLER] || validatorAliasObj[RESULT_HANDLER] || validators[RESULT_HANDLER];

            error = resultHandler(validator.apply(validators, args));
        } catch (err) {
            var exceptionHandler = validatorObj[EXCEPTION_HANDLER] || validatorAliasObj[EXCEPTION_HANDLER] || validators[EXCEPTION_HANDLER];

            if (typeof exceptionHandler === 'function') {
                error = exceptionHandler(err);
            } else {
                throw err;
            }
        }

        function handleError(error) {
            if (error) {
                var _ret = function () {
                    var errorObj = (typeof error === 'undefined' ? 'undefined' : _typeof(error)) === 'object' ? error : null; //in case if we rewrite message in options and want to use fields from error object in the placeholders
                    var message = options[MESSAGE] || validatorObj[MESSAGE] || validatorAliasObj[MESSAGE];

                    if (message) {
                        error = message;
                    }

                    var formattedErrorMessage = validators.formatMessage(error, assign({ validator: alias || name, value: value }, errorObj, options));
                    var format = validatorObj[ERROR_FORMAT] || validatorAliasObj[ERROR_FORMAT] || validators[ERROR_FORMAT];

                    if (format) {
                        if (typeof formattedErrorMessage === 'string') {
                            formattedErrorMessage = { message: formattedErrorMessage };
                        }

                        if (format.$options) {
                            format = assign({}, format);

                            Object.keys(options).forEach(function (key) {
                                if (!MESSAGE_REGEXP.test(key) && typeof options[key] !== 'function') {
                                    format[key] = options[key];
                                }
                            });
                        }
                        delete format.$options;

                        if (format.$origin) {
                            format = assign({}, format, formattedErrorMessage);
                        }
                        delete format.$origin;

                        return {
                            v: validators.formatMessage(format, assign({ validator: alias || name, value: value }, options, formattedErrorMessage))
                        };
                    }

                    return {
                        v: formattedErrorMessage
                    };
                }();

                if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
            }
        }

        return (typeof error === 'undefined' ? 'undefined' : _typeof(error)) === 'object' && typeof error.then === 'function' ? error.then(handleError) : handleError(error);
    };
}
758422
function normalizeValidator(validator) {
	        if (validator.validate !== undefined) {
	            return function (c) { return validator.validate(c); };
	        }
	        else {
	            return validator;
	        }
	    }
427612
def validate(cls, **kwargs):
        '''  '''
        # errors can store multiple errors
        # obj is an instance in case validation succeeds
        # redis is needed for database validation
        errors = ValidationErrors()
        obj = cls()
        redis = cls.get_redis()

        # Check the fields
        for fieldname, field in obj.proxy:
            if not field.fillable:
                value = field.default
            else:
                try:
                    value = field.validate(kwargs.get(fieldname), redis)
                except BadField as e:
                    errors.append(e)
                    continue

            setattr(
                obj,
                fieldname,
                value
            )

        # Check for custom validation rules
        for fieldname in dir(cls):
            rule = getattr(cls, fieldname)

            if hasattr(rule, '_is_validation_rule') and rule._is_validation_rule:
                try:
                    rule(obj)
                except BadField as e:
                    errors.append(e)

        # Trigger errors if any
        if errors.has_errors():
            raise errors

        # Return the object with the new data set
        return obj