validate method

  1. @override
JarResult validate(
  1. dynamic value, [
  2. Map<String, dynamic>? allValues,
  3. String? path,
  4. Object? root,
])
override

Implementation

@override
JarResult validate(dynamic value,
    [Map<String, dynamic>? allValues, String? path, Object? root]) {
  final effectiveRoot = root ?? value;
  if (value == null) {
    return super.validate(null, allValues, path, effectiveRoot);
  }

  if (value is! List) {
    return JarResult.error('Expected a list');
  }

  List<T>? typedList;
  try {
    typedList = List<T>.from(value);
  } catch (e) {
    return JarResult.error('Failed to convert list to required type');
  }

  final listResult = super.validate(typedList, allValues, path, effectiveRoot);
  if (!listResult.isValid) {
    return listResult;
  }
  final workingList =
      listResult.value is List ? listResult.value as List : typedList;

  if (workingList.isNotEmpty && elementSchema != null) {
    final errors = <int, String>{};
    final output = [];
    for (var i = 0; i < workingList.length; i++) {
      final childPath = path == null ? '$i' : '$path.$i';
      final elementResult = elementSchema!
          .validate(workingList[i], allValues, childPath, effectiveRoot);
      output.add(elementResult.value);
      if (!elementResult.isValid) {
        errors[i] = elementResult.error!;
      }
    }
    if (errors.isNotEmpty) {
      return JarResult.error(
          'Errors in list elements', {'elementErrors': errors});
    }
    return JarResult.success(output);
  }

  return JarResult.success(workingList);
}