check method

ValidationResult check(
  1. Map inputData
)

Validates, and filters input data.

Implementation

ValidationResult check(Map inputData) {
  List<String> errors = [];
  var input = Map.from(inputData);
  Map<String, dynamic> data = {};

  for (String key in defaultValues.keys) {
    if (!input.containsKey(key)) {
      var value = defaultValues[key];
      input[key] = value is DefaultValueFunction ? value() : value;
    }
  }

  for (String field in forbiddenFields) {
    if (input.containsKey(field)) {
      if (!customErrorMessages.containsKey(field)) {
        errors.add("'$field' is forbidden.");
      } else {
        errors.add(customError(field, input[field]));
      }
    }
  }

  for (String field in requiredFields) {
    if (!_hasContextValidators(rules[field] ?? [])) {
      if (!input.containsKey(field)) {
        if (!customErrorMessages.containsKey(field)) {
          errors.add("'$field' is required.");
        } else {
          errors.add(customError(field, 'none'));
        }
      }
    }
  }

  // Run context validators.

  for (var key in input.keys) {
    if (key is String && rules.containsKey(key)) {
      var valid = true;
      var value = input[key];
      var description = StringDescription("'$key': expected ");

      for (var matcher in rules[key]) {
        if (matcher is ContextValidator) {
          if (!matcher.validate(key, input)) {
            errors.add(matcher.errorMessage(description, key, input).toString().trim());
            valid = false;
          }
        }
      }

      if (valid) {
        for (Matcher matcher in rules[key]) {
          try {
            if (matcher is Validator) {
              var result = matcher.check(value as Map);

              if (result.errors.isNotEmpty) {
                errors.addAll(result.errors);
                valid = false;
                break;
              }
            } else {
              bool result;

              if (matcher is ContextAwareMatcher) {
                result = matcher.matchesWithContext(value, key, input, {});
              } else {
                result = matcher.matches(value, {});
              }

              if (!result) {
                if (!customErrorMessages.containsKey(key)) {
                  errors.add(matcher.describe(description).toString().trim());
                }
                valid = false;
                break;
              }
            }
          } catch (e) {
            errors.add(e.toString());
            valid = false;
            break;
          }
        }
      }

      if (valid) {
        data[key] = value;
      } else if (customErrorMessages.containsKey(key)) {
        errors.add(customError(key, input[key]));
      }
    }
  }

  if (errors.isNotEmpty) {
    return ValidationResult().._errors.addAll(errors);
  }

  return ValidationResult().._data.addAll(data);
}