validate method
List<ConstrainViolation>
validate(
- dynamic object, {
- String? parentFieldName,
- String? fieldSeparator,
- bool? throwExceptionOnFail = false,
override
Implementation
@override
List<ConstrainViolation> validate(
dynamic object, {
String? parentFieldName,
String? fieldSeparator,
bool? throwExceptionOnFail = false,
}) {
//if its null set the default base-name as parent field name, and,
//the default field-separator
//When: usually the first time its called if user dont specify it this default values are used
parentFieldName ??= baseName;
fieldSeparator ??= defaultFieldSeparator;
throwExceptionOnFail ??= defaultTrowException;
List<ConstrainViolation> violations = [];
if (object is List) {
for (var i = 0; i < object.length; ++i) {
dynamic element = object[i];
violations.addAll(
validate(
element,
parentFieldName: '$parentFieldName[$i]',
),
);
}
} else if (object is Map) {
for (var element in object.entries) {
violations.addAll(
validate(
element.value,
parentFieldName: '$parentFieldName[${element.key}]',
),
);
}
} else {
if (object is Validatable) {
violations.addAll(
object.validate(
parentFieldName: parentFieldName,
fieldSeparator: fieldSeparator,
),
);
} else {
var objectMirror = reflect(object);
var classMirror = objectMirror.type;
//process class level annotations
List<Valid> rootValid = _getValid(classMirror.metadata);
violations.addAll(
processValid(
valid: rootValid,
fieldValue: object,
fieldName: parentFieldName!,
),
);
for (var declaration in classMirror.declarations.values) {
if (declaration is VariableMirror && !declaration.isStatic) {
var fieldName =
'$parentFieldName$fieldSeparator${_getFieldName(declaration)}';
var fieldValue =
objectMirror.getField(declaration.simpleName).reflectee;
List<Valid> valid = _getValid(declaration.metadata);
violations.addAll(
processValid(
valid: valid,
fieldValue: fieldValue,
fieldName: fieldName,
),
);
if (doRecursiveType(fieldValue)) {
violations.addAll(
validate(
fieldValue,
parentFieldName: fieldName,
),
);
}
}
}
}
}
if (throwExceptionOnFail == true && violations.isNotEmpty) {
throw ValidationException(violations: violations);
} else {
return violations;
}
}