check method
Validates, and filters input data.
Implementation
ValidationResult check(Map inputData) {
var errors = <String>[];
var input = Map.from(inputData);
var data = <String, dynamic>{};
for (var key in defaultValues.keys) {
if (!input.containsKey(key)) {
var value = defaultValues[key];
input[key] = value is DefaultValueFunction ? value() : value;
}
}
for (var field in forbiddenFields) {
if (input.containsKey(field)) {
if (!customErrorMessages.containsKey(field)) {
errors.add("'$field' is forbidden.");
} else {
errors.add(customError(field, input[field]));
}
}
}
for (var 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 ");
var rulesList = rules[key] ?? [];
for (var matcher in rulesList) {
if (matcher is ContextValidator) {
if (!matcher.validate(key, input)) {
errors.add(matcher
.errorMessage(description, key, input)
.toString()
.trim());
valid = false;
}
}
}
if (valid) {
var rulesList = rules[key] ?? [];
for (var matcher in rulesList) {
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) {
if (e is ValidationException) {
errors.add(e.errors.first);
} else {
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);
}