validate method

Map<String, List<ValidationResult>> validate(
  1. Map<String, dynamic> data
)

Implementation

Map<String, List<ValidationResult>> validate(Map<String, dynamic> data) {
  final code = """
      ajv.validate("objSchema",${json.encode(data)});
      JSON.stringify(ajv.errors);
    """;
  final jsResult = jsRuntime.evaluate(code);

  final valueResult = json.decode(jsResult.stringResult);
  final errorList = ValidationResult.listFromJson(
      valueResult is int ? [] : valueResult ?? []);

  Map<String, List<ValidationResult>> errorMap = {};
  for (var error in errorList) {
    if (error.keyword == 'required') {
      final fieldKey = error.params['missingProperty'];
      if (fieldKey != null) {
        errorMap[fieldKey] = [...(errorMap[fieldKey] ?? []), error];
      }
    }

    if (error.dataPath != null) {
      final resultArr = error.dataPath?.split('.') ?? [];
      final fieldKey = resultArr.length > 1 ? resultArr.last : null;
      if (fieldKey != null) {
        errorMap[fieldKey] = [...(errorMap[fieldKey] ?? []), error];
      }
    }
  }

  return errorMap;
}