validateBody method

Future<Map<String, dynamic>> validateBody(
  1. Map<String, dynamic> rules, {
  2. Map<String, String>? messages,
})

Validates the request body input against the given rules.

Throws ValidationException if validation fails. Returns the validated input data if validation passes.

Implementation

Future<Map<String, dynamic>> validateBody(
  Map<String, dynamic> rules, {
  Map<String, String>? messages,
}) async {
  final input = await _bodyParser.parse();

  // Merge uploaded files into the input data for validation
  if (_bodyParser.files != null) {
    input.addAll(_bodyParser.files as Map<String, dynamic>);
  }

  final validator =
      InputValidator(input, rules, customMessages: messages ?? {});

  if (!await validator.passes()) {
    throw ValidationException(validator.errors);
  }

  // Return only the validated data that are in the rules
  return {
    for (var key in rules.keys)
      if (input.containsKey(key)) key: input[key],
  };
}