Field-level input validation error collector
C++
#include <exception>
#include <map>
#include <string>
#include <vector>
using Errors = std::map<std::string, std::vector<std::string>>;
Errors validate(const std::map<std::string, std::string>& input) {
Errors errs;
auto get = [&](const char* k) { auto it = input.find(k); return it == input.end() ? std::string{} : it->second; };
if (get("name").empty()) errs["name"].push_back("required");
const std::string email = get("email");
if (email.find('@') == std::string::npos) errs["email"].push_back("must contain @");
if (!get("age").empty()) {
try { if (std::stoi(get("age")) < 18) errs["age"].push_back("must be 18 or older"); }
catch (const std::exception&) { errs["age"].push_back("must be a number"); }
}
return errs;
}