TODO: Add test cases for validations
496869
def valid_attribute?(attribute)
    case attr_type_for(attribute)
    when :bool
      validate_class_for(attribute, [TrueClass, FalseClass])
    when :datetime, :datetimecombo
      validate_class_for(attribute, [DateTime])
    when :int
      validate_class_for(attribute, [Fixnum, Float])
    else 
      if @attributes[attribute].blank?
        add_error(attribute, "cannot be blank")
      end
    end
  end
1308704
function validateParameters() {
		grunt.verbose.writeln( 'BowerMap::validateParameters' );
		//flag used to determine if validation passes
		var check = true;

		//lib path must be set
		//TODO: get default bowerpath from .bowerrc
		bowerPath = bowerPath || "bower_components";
		if ( typeof bowerPath !== 'string' ) {
			grunt.log.error( 'Bower path must be a string.' );
			check = false;
		}

		//lib path must be set
		if ( !destPath || typeof destPath !== 'string' ) {
			grunt.log.error( 'Default destination path must be configured.' );
			check = false;
		}

		//shim isn't required, but must be a key value object
		shim = shim || {};
		if ( typeof shim !== "object" ) {
			grunt.log.error( 'shim must be an object.' );
			check = false;
		}

		//map isn't required, but must be a key value object
		map = map || {};
		if ( typeof map !== "object" ) {
			grunt.log.error( 'map must be an object.' );
			check = false;
		}

		//ignore isn't required, but must be an array
		ignore = ignore || [];
		if ( !Array.isArray( ignore )  ) {
			grunt.log.error( 'ignore must be an array of strings.' );
			check = false;
		}

		//maintainCommonPaths isn't required, but must be boolean
		maintainCommonPaths = maintainCommonPaths || false;
		if ( typeof maintainCommonPaths !== "boolean" ) {
			grunt.log.error( 'maintainCommonPaths must be a boolean value.' );
			check = false;
		}

		//useNamespace isn't required, but must be undefined or boolean
		if ( useNamespace !== undefined && typeof useNamespace !== "boolean" ) {
			grunt.log.error( 'useNamespace must be boolean or undefined.' );
			check = false;
		}

		//extensions isn't required, but must be an array
		extensions = extensions || undefined;
		if ( extensions !== undefined && !Array.isArray( extensions )  ) {
			grunt.log.error( 'extensions must be an array or undefined.' );
			check = false;
		}

		return check;
	}
821018
public function validate()
	{
		$this->errors->set();

		foreach ($this->rules as $key => $rule) {
			list ($fields, $type, $options) = $this->parseRule($rule);

			if (!$validator = $this->validators->$type) {
				$validator = $this->create($type);
				$this->validators->$type = $validator;
			}

			foreach ($fields as $key => $field) {
				$value = $this->dataSet->$field;

				if (!$validator->validate($value, $options)) {
					$this->addErrors($field, $validator->getErrors());
				}
			}
		}

		return !$this->hasErrors();
	}
1147465
function(input) {
		var needstesting = !this._matches.length;
		if (needstesting || this._matches.every(function(match) {
			return match.$instanceid !== input.$instanceid;
		})) {
			return this._maybeinput(input);
		}
		return false;
	}
1021952
function(args, types) {
		this._validating = true;
		var is = this._match(args, types);
		this._validating = false;
		return is;
	}
552606
public function validate()
    {
        $registers = $this->getRegisters();
        $triggerFunctions = $this->getTriggerFunctions();
        $globalActions = $this->getGlobalActions();
        $initialActions = $this->getInitialActions();
        $commonActions = $this->getCommonActions();
        $steps = $this->getSteps();
        $splits = $this->getSplits();
        $joins = $this->getJoins();


        ValidationHelper::validate($registers);
        ValidationHelper::validate($triggerFunctions);
        ValidationHelper::validate($globalActions);
        ValidationHelper::validate($initialActions);
        ValidationHelper::validate($commonActions);
        ValidationHelper::validate($steps);
        ValidationHelper::validate($splits);
        ValidationHelper::validate($joins);


        $actions = [];

        foreach ($globalActions as $action) {
            $actionId = $action->getId();
            if (array_key_exists($actionId, $actions)) {
                $errMsg = sprintf(
                    'Ошибка валидация. Действие с id %s уже существует',
                    $actionId
                );
                throw new InvalidWorkflowDescriptorException($errMsg);
            }
            $actions[$actionId] = $actionId;
        }

        foreach ($steps as $step) {
            $j = $step->getActions();

            foreach ($j as $action) {
                if (!$action->isCommon()) {
                    $actionId = $action->getId();
                    if (array_key_exists($actionId, $actions)) {
                        $errMsg = sprintf(
                            'Действие с id %s найденное у шага %s является дубликатом',
                            $actionId,
                            $step->getId()
                        );
                        throw new InvalidWorkflowDescriptorException($errMsg);
                    }
                    $actions[$actionId] = $actionId;
                }
            }
        }


        foreach ($commonActions as $action) {
            $actionId = $action->getId();
            if (array_key_exists($actionId, $actions)) {
                $errMsg = sprintf(
                    'common-action  с id %s является дубликатом',
                    $actionId
                );
                throw new InvalidWorkflowDescriptorException($errMsg);
            }
        }


        $this->validateDtd();
    }
321673
public function validate() {

		if ($this->getCurrency() === null) {
			throw new ValidationException("'currency' can't be null", 'currency', $this);
		}
		if ($this->getProduct() === null) {
			throw new ValidationException("'product' can't be null", 'product', $this);
		}
		if ($this->getSubscription() === null) {
			throw new ValidationException("'subscription' can't be null", 'subscription', $this);
		}
	}
776271
public function validate()
    {
        $commonActions = $this->getCommonActions();
        $actions = $this->getActions();
        $hasActions = $this->hasActions;

        if ($hasActions && 0 === count($commonActions) && 0 === $actions->count()) {
            $stepName = (string)$this->getName();
            $errMsg = sprintf('Шаг %s должен содержать одни действие или одно общее действие', $stepName);
            throw new InvalidWorkflowDescriptorException($errMsg);
        }

        if (-1 === $this->getId()) {
            $errMsg = 'В качестве id шага нельзя использовать -1, так как это зарезериврованное значение';
            throw new InvalidWorkflowDescriptorException($errMsg);
        }

        $preFunctions = $this->getPreFunctions();
        $postFunctions = $this->getPostFunctions();
        $actions = $this->getActions();
        $permissions = $this->getPermissions();

        ValidationHelper::validate($preFunctions);
        ValidationHelper::validate($postFunctions);
        ValidationHelper::validate($actions);
        ValidationHelper::validate($permissions);

        $workflowDescriptor = $this->getParent();
        if (!$workflowDescriptor instanceof WorkflowDescriptor) {
            $errMsg = sprintf('Родительский элемент для шага должен реализовывать %s', WorkflowDescriptor::class);
            throw new InvalidWorkflowDescriptorException($errMsg);
        }
        foreach ($commonActions as $actionId) {
            try {
                $commonActionReference = $workflowDescriptor->getCommonAction($actionId);

                if (null === $commonActionReference) {
                    $stepName = (string)$this->getName();
                    $errMsg = sprintf('Common-action %s указанное для шага %s не существует', $actionId, $stepName);
                    throw new InvalidWorkflowDescriptorException($errMsg);
                }
            } catch (\Exception $e) {
                $actionIdStr = (string)$actionId;
                $errMsg = sprintf('Некорректный id для common-action: id %s', $actionIdStr);
                throw  new InvalidWorkflowDescriptorException($errMsg, $e->getCode(), $e);
            }
        }
    }
975150
function assembleValidation(validation) {
  if (!_.isPlainObject(validation)) {
    validation = {rule: validation, params: []};
  }
  if (_.isString(validation.rule)) {
    var splitRule = validation.rule.split(':');
    validation.rule = splitRule[0];
    if (_.isEmpty(validation.params)) {
      validation.params = _.tail(splitRule);
    }
  } else if (!_.isFunction(validation.rule)) {
    throw new TypeError('Invalid validation');
  }
  return validation;
}
1284697
public static void validateValues(Object actualValue, Object expectedValue, String pathExpression, TestContext context)
            throws ValidationException {
        try {
            if (actualValue != null) {
                Assert.isTrue(expectedValue != null,
                        ValidationUtils.buildValueMismatchErrorMessage(
                                "Values not equal for element '" + pathExpression + "'", null, actualValue));

                if (expectedValue instanceof Matcher) {
                    Assert.isTrue(((Matcher) expectedValue).matches(actualValue),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not matching for element '" + pathExpression + "'", expectedValue, actualValue));
                    return;
                }

                if (!(expectedValue instanceof String)) {
                    Object converted = TypeConversionUtils.convertIfNecessary(actualValue, expectedValue.getClass());

                    if (converted == null) {
                        throw new CitrusRuntimeException(String.format("Failed to convert value '%s' to required type '%s'", actualValue, expectedValue.getClass()));
                    }

                    if (converted instanceof List) {
                        Assert.isTrue(converted.toString().equals(expectedValue.toString()),
                                ValidationUtils.buildValueMismatchErrorMessage(
                                        "Values not equal for element '" + pathExpression + "'", expectedValue.toString(), converted.toString()));
                    } else if (converted instanceof String[]) {
                        String convertedDelimitedString = StringUtils.arrayToCommaDelimitedString((String[]) converted);
                        String expectedDelimitedString = StringUtils.arrayToCommaDelimitedString((String[]) expectedValue);

                        Assert.isTrue(convertedDelimitedString.equals(expectedDelimitedString),
                                ValidationUtils.buildValueMismatchErrorMessage(
                                        "Values not equal for element '" + pathExpression + "'", expectedDelimitedString, convertedDelimitedString));
                    } else if (converted instanceof byte[]) {
                        String convertedBase64 = Base64.encodeBase64String((byte[]) converted);
                        String expectedBase64 = Base64.encodeBase64String((byte[]) expectedValue);

                        Assert.isTrue(convertedBase64.equals(expectedBase64),
                                ValidationUtils.buildValueMismatchErrorMessage(
                                        "Values not equal for element '" + pathExpression + "'", expectedBase64, convertedBase64));
                    } else {
                        Assert.isTrue(converted.equals(expectedValue),
                                ValidationUtils.buildValueMismatchErrorMessage(
                                        "Values not equal for element '" + pathExpression + "'", expectedValue, converted));
                    }
                } else {
                    String expectedValueString = expectedValue.toString();
                    String actualValueString;
                    if (List.class.isAssignableFrom(actualValue.getClass())) {
                        actualValueString = StringUtils.arrayToCommaDelimitedString(((List)actualValue).toArray(new Object[((List)actualValue).size()]));
                        expectedValueString = expectedValueString.replaceAll("^\\[", "").replaceAll("\\]$", "").replaceAll(",\\s", ",");
                    } else {
                        actualValueString = actualValue.toString();
                    }

                    if (ValidationMatcherUtils.isValidationMatcherExpression(String.valueOf(expectedValueString))) {
                        ValidationMatcherUtils.resolveValidationMatcher(pathExpression,
                                actualValueString,
                                String.valueOf(expectedValueString),
                                context);
                    } else {
                        Assert.isTrue(actualValueString.equals(expectedValueString),
                                ValidationUtils.buildValueMismatchErrorMessage(
                                        "Values not equal for element '" + pathExpression + "'", expectedValueString, actualValueString));
                    }
                }
            } else if (expectedValue != null) {
                if (expectedValue instanceof Matcher) {
                    Assert.isTrue(((Matcher) expectedValue).matches(null),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not matching for element '" + pathExpression + "'", expectedValue, null));
                } else if (expectedValue instanceof String) {
                    String expectedValueString = expectedValue.toString();

                    if (ValidationMatcherUtils.isValidationMatcherExpression(expectedValueString)) {
                        ValidationMatcherUtils.resolveValidationMatcher(pathExpression,
                                null,
                                expectedValueString,
                                context);
                    } else {
                        Assert.isTrue(!StringUtils.hasText(expectedValueString),
                                ValidationUtils.buildValueMismatchErrorMessage(
                                        "Values not equal for element '" + pathExpression + "'", expectedValueString, null));
                    }
                } else {
                    throw new ValidationException("Validation failed: " + ValidationUtils.buildValueMismatchErrorMessage(
                            "Values not equal for element '" + pathExpression + "'", expectedValue, null));
                }
            }
        } catch (IllegalArgumentException | AssertionError e) {
            throw new ValidationException("Validation failed:", e);
        }
    }
727267
function validate(values) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var s = this;

    var _tv4$validateMultiple = tv4.validateMultiple(values, s),
        valid = _tv4$validateMultiple.valid,
        errors = _tv4$validateMultiple.errors;

    if (valid) {
      return null;
    }

    var assign = options.assign,
        _options$name = options.name,
        name = _options$name === void 0 ? 'SchemaError' : _options$name;
    var _s$schema = s.schema,
        schema = _s$schema === void 0 ? {} : _s$schema;
    var error = new Error("Validation failed with schema: ".concat(schema.title || schema.id || schema.description));
    return Object.assign(error, {
      id: uuid.v4(),
      name: name,
      errors: errors,
      schema: schema,
      values: values,
      engine: 'tv4'
    }, assign);
  }
1325035
function beforeValidate (controller, args) {
    // get model from controller
    var model = controller.model
    // get model data from input
    var data = args[model.name]
    // get schema id
    var schemaId = args.meta || !model.schemaDataId
        ? model.schemaId
        : model.schemaDataId
    // if validating meta data convert property names to columns names
    if (args.meta) {
        // clone data before modifying - shallow since only property names are
        // being modified
        data = _.clone(data)
        // iterate over all data properties
        _.each(data, (val, key) => {
            // get column name for key
            var columnName = model.columnName(key)
            // if property does not map to column then skip
            if (!columnName) {
                return
            }
            // use column name for validation
            if (columnName !== key) {
                // copy value to column name
                data[columnName] = val
                // delete entry for original property
                delete data[key]
            }
        })
    }
    // get global validator
    var validator = model.global().validator
    // throw error if validation failed
    if (!validator.validate(schemaId, data)) {
        // throw error
        httpError(400, 'Validation Error', validator.errors)
    }
}
1093884
@Override
	public List<ParsingError> doValidate() {

		List<ParsingError> result = new ArrayList<> ();
		if( Utils.isEmptyOrWhitespaces( this.newInstanceName ))
			result.add( error( ErrorCode.CMD_MISSING_INSTANCE_NAME ));
		else if( ! this.newInstanceName.matches( ParsingConstants.PATTERN_FLEX_ID ))
			result.add( error( ErrorCode.CMD_INVALID_INSTANCE_NAME, name( this.newInstanceName )));

		if( ! this.context.instanceExists( this.instancePath )) {
			result.add( error( ErrorCode.CMD_NO_MATCHING_INSTANCE, instance( this.instancePath )));

		} else {
			String parentInstancePath = this.instancePath.replaceFirst( "/[^/]+$", "" );
			String siblingPath = parentInstancePath + "/" + this.newInstanceName;
			if( this.context.instanceExists( siblingPath ))
				result.add( error( ErrorCode.CMD_CONFLICTING_INSTANCE_NAME, conflicting( siblingPath )));
		}

		return result;
	}
79882
public function validate() {

		if ($this->getEndAction() === null) {
			throw new ValidationException("'endAction' can't be null", 'endAction', $this);
		}
		if ($this->getPlannedEndDate() === null) {
			throw new ValidationException("'plannedEndDate' can't be null", 'plannedEndDate', $this);
		}
		if ($this->getSubscription() === null) {
			throw new ValidationException("'subscription' can't be null", 'subscription', $this);
		}
	}
404430
@Override
	public List<ParsingError> doValidate() {

		List<ParsingError> result = new ArrayList<> ();
		if( Utils.isEmptyOrWhitespaces( this.targetId ))
			result.add( error( ErrorCode.CMD_INVALID_TARGET_ID, value( this.targetId )));

		Instance resolvedInstance;
		if(( resolvedInstance = this.context.resolveInstance( this.scopedInstancePath )) == null)
			result.add( error( ErrorCode.CMD_NO_MATCHING_INSTANCE, instance( this.scopedInstancePath )));
		else if( ! InstanceHelpers.isTarget( resolvedInstance ))
			result.add( error( ErrorCode.CMD_NOT_A_SCOPED_INSTANCE ));

		return result;
	}
69602
private List<TestCaseDef> getBaseValidCases( FunctionInputDef inputDef, VarTupleSet validTuples, List<TestCaseDef> baseCases)
    {
    logger_.debug( "{}: Extending valid base test cases", inputDef);

    Iterator<TestCaseDef> validBaseCases =
      IteratorUtils.filteredIterator(
        baseCases.iterator(),
        testCase -> testCase.getInvalidVar() == null);

    List<TestCaseDef> testCases = extendBaseCases( inputDef, validTuples, validBaseCases);

    logger_.info( "{}: Extended {} valid base test cases", inputDef, testCases.size());
    return testCases;
   }
42751
function prepValidations(validations) {
  validations = _.cloneDeep(validations);
  for (var key in validations) {
    var validation = validations[key];
    if (!_.isArray(validation)) validations[key] = validation = [validation];
    for (var i = 0, l = validation.length; i < l; i++) {
      validation[i] = assembleValidation(validation[i]);
    }
  }
  return validations;
}