validate method

ValidationResults validate(
  1. dynamic instance, {
  2. bool reportMultipleErrors = false,
  3. bool parseJson = false,
  4. bool? validateFormats,
})

Validate the instance against the Validator's JsonSchema

Implementation

ValidationResults validate(
  dynamic instance, {
  bool reportMultipleErrors = false,
  bool parseJson = false,
  bool? validateFormats,
}) {
  final rootSchema = _rootSchema;
  if (rootSchema == null) {
    throw ArgumentError();
  }
  // Reference: https://json-schema.org/draft/2019-09/release-notes.html#format-vocabulary
  // By default, formats are validated on a best-effort basis from draft4 through draft7.
  // Starting with Draft 2019-09, formats shouldn't be validated by default.
  _validateFormats =
      validateFormats ?? rootSchema.schemaVersion <= SchemaVersion.draft7;

  dynamic data = instance;
  if (parseJson && instance is String) {
    try {
      data = json.decode(instance);
    } catch (e) {
      throw ArgumentError(
          'JSON instance provided to validate is not valid JSON.');
    }
  }

  _reportMultipleErrors = reportMultipleErrors;
  _errors = [];
  if (!_reportMultipleErrors) {
    try {
      _validate(rootSchema, data);
      return ValidationResults(_errors, _warnings);
    } on FormatException {
      return ValidationResults(_errors, _warnings);
    } on Exception catch (e) {
      _logger.shout('Unexpected Exception: $e');
      rethrow;
    }
  }

  _validate(rootSchema, data);
  return ValidationResults(_errors, _warnings);
}