Question 3
Back to Exercise
Validate sign-up data with a vector of {message, lambda} rules (name length, email has @, age range, password strength) and print every failed rule for each user.
Solution
#include <algorithm>
#include <cctype>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
struct User { std::string name, email, password; int age; };
int main() {
std::vector<std::pair<std::string, std::function<bool(const User&)>>> rules{
{"name needs 3+ letters", [](const User& u) { return u.name.size() >= 3; }},
{"email needs @", [](const User& u) { return u.email.find('@') != std::string::npos; }},
{"age must be 13-120", [](const User& u) { return u.age >= 13 && u.age <= 120; }},
{"password needs 8+ chars and a digit", [](const User& u) {
return u.password.size() >= 8 && std::any_of(u.password.begin(), u.password.end(), [](unsigned char c) { return std::isdigit(c); });
}},
};
std::vector<User> users{{"Asha", "asha@mail.in", "learn2code", 21}, {"Jo", "jo.mail.in", "short", 10}, {"Ravi", "ravi@x.in", "password", 30}};
for (const auto& u : users) {
std::cout << u.name << ':';
int failed = 0;
for (const auto& [msg, ok] : rules) if (!ok(u)) { std::cout << "\n - " << msg; ++failed; }
std::cout << (failed ? "\n" : " valid\n");
}
return 0;
}
Asha: valid Jo: - name needs 3+ letters - email needs @ - age must be 13-120 - password needs 8+ chars and a digit Ravi: - password needs 8+ chars and a digit
Rules are data: a message and a predicate. Adding a rule never touches the checking loop. The password rule even uses a nested lambda.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!