Basic Programming Coding example
Project-Level / Real-Time Validation Examples (with output)
Multiple conditions inside and_then
Using filter() (Cleaner & Recommended)
Using match with guard (Very Clean Rust Way)
Return different error messages per condition (Better for APIs)
Full Updated Payment Example (Multiple Conditions + Currency)
User Registration Validation (username + email + age)
Product Order Validation (price + quantity + stock)
Login Validation (username + password + role)
Booking Validation (start_time + end_time + seats)
Payment Validation (amount + currency + user_id + status)
Basic Programming Coding example
1) Validate username is not empty
fn main() {
let input = "ashwani";
let username = if input.trim().is_empty() { None } else { Some(input.trim()) };
match username {
Some(u) => println!("OK: username = {}", u),
None => println!("ERR: username is required"),
}
}
Output
OK: username = ashwani
2) Validate number is positive (parse + check)
fn main() {
let raw = "12";
let n = raw.parse::<i32>().ok().and_then(|v| if v > 0 { Some(v) } else { None });
match n {
Some(v) => println!("OK: positive number = {}", v),
None => println!("ERR: invalid or not positive"),
}
}
Output
OK: positive number = 12
3) Validate age >= 18
fn main() {
let raw_age = "17";
let age = raw_age.parse::<u8>().ok().and_then(|a| if a >= 18 { Some(a) } else { None });
match age {
Some(a) => println!("OK: allowed, age={}", a),
None => println!("ERR: must be 18+"),
}
}
Output
ERR: must be 18+
4) Validate email contains '@' and '.'
fn main() {
let email_raw = "test@gmail.com";
let email = {
let e = email_raw.trim();
if e.contains('@') && e.contains('.') { Some(e) } else { None }
};
match email {
Some(e) => println!("OK: email={}", e),
None => println!("ERR: invalid email"),
}
}
Output
OK: email=test@gmail.com
5) Validate OTP length exactly 6 digits
fn main() {
let otp_raw = "12345a";
let otp = {
let s = otp_raw.trim();
if s.len() == 6 && s.chars().all(|c| c.is_ascii_digit()) { Some(s) } else { None }
};
match otp {
Some(v) => println!("OK: otp={}", v),
None => println!("ERR: OTP must be 6 digits"),
}
}
Output
ERR: OTP must be 6 digits
6) Validate minimum password length (>= 8)
fn main() {
let pass = "secret12";
let valid = if pass.len() >= 8 { Some(pass) } else { None };
match valid {
Some(_) => println!("OK: password length valid"),
None => println!("ERR: password too short"),
}
}
Output
OK: password length valid
7) Validate allowed role using match
fn main() {
let role_raw = "admin";
let role = match role_raw {
"admin" => Some("Admin"),
"viewer" => Some("Viewer"),
_ => None,
};
match role {
Some(r) => println!("OK: role={}", r),
None => println!("ERR: role not allowed"),
}
}
Output
OK: role=Admin
8) Validate list is not empty
fn main() {
let items: Vec<i32> = vec![];
let non_empty = if items.is_empty() { None } else { Some(items.len()) };
match non_empty {
Some(n) => println!("OK: items count={}", n),
None => println!("ERR: list cannot be empty"),
}
}
Output
ERR: list cannot be empty
9) Validate string max length <= 10
fn main() {
let city = "Dhanbad";
let ok = if city.chars().count() <= 10 { Some(city) } else { None };
match ok {
Some(v) => println!("OK: city={}", v),
None => println!("ERR: city too long"),
}
}
Output
OK: city=Dhanbad
10) Validate two inputs together (both required)
fn main() {
let u = "ashwani";
let p = "";
let username = if u.trim().is_empty() { None } else { Some(u.trim()) };
let password = if p.trim().is_empty() { None } else { Some(p.trim()) };
match (username, password) {
(Some(u), Some(_)) => println!("OK: login inputs present, user={}", u),
(None, _) => println!("ERR: username missing"),
(_, None) => println!("ERR: password missing"),
}
}
Output
ERR: password missing
1️⃣ and_then ≡ filter
Syntax
amount.and_then(|a| if a > 0 { Some(a) } else { None })
Equivalent to:
amount.filter(|a| *a > 0)
Program
fn main() {
let amount = Some(10);
let result = amount.filter(|a| *a > 0);
println!("{:?}", result);
}
Output
Some(10)
✅ 2️⃣ Multiple Conditions with and_then
Syntax
value.and_then(|v| {
if cond1 && cond2 { Some(v) } else { None }
})
Equivalent to:
value.filter(|v| cond1 && cond2)
Program
fn main() {
let num = Some(20);
let result = num.filter(|n| *n > 10 && *n < 30);
println!("{:?}", result);
}
Output
Some(20)
✅ 3️⃣ map vs and_then
Syntax
opt.map(|v| v * 2)
Used when returning value directly.
opt.and_then(|v| Some(v * 2))
Equivalent here.
Program
fn main() {
let x = Some(5);
let result = x.map(|v| v * 2);
println!("{:?}", result);
}
Output
Some(10)
✅ 4️⃣ match vs if let
Syntax
match opt {
Some(v) => println!("{}", v),
None => println!("None"),
}
Equivalent to:
if let Some(v) = opt {
println!("{}", v);
}
Program
fn main() {
let val = Some(100);
if let Some(v) = val {
println!("Value: {}", v);
}
}
Output
Value: 100
✅ 5️⃣ unwrap_or for Default
Syntax
opt.unwrap_or(default_value)
Program
fn main() {
let val: Option<i32> = None;
let result = val.unwrap_or(50);
println!("{}", result);
}
Output
50
✅ 6️⃣ unwrap_or_else (Lazy Evaluation)
Syntax
opt.unwrap_or_else(|| compute())
Program
fn main() {
let val: Option<i32> = None;
let result = val.unwrap_or_else(|| 99);
println!("{}", result);
}
Output
99
✅ 7️⃣ Combine Multiple Options in Match (Tuple Match)
Syntax
match (opt1, opt2) {
(Some(a), Some(b)) => ...
_ => ...
}
Program
fn main() {
let a = Some(5);
let b = Some(10);
match (a, b) {
(Some(x), Some(y)) => println!("Sum = {}", x + y),
_ => println!("Missing value"),
}
}
Output
Sum = 15
✅ 8️⃣ Using ? Operator (Shortcut for match)
Syntax
let v = opt?;
Equivalent to:
match opt {
Some(v) => v,
None => return None,
}
Program
fn double(opt: Option<i32>) -> Option<i32> {
let v = opt?;
Some(v * 2)
}
fn main() {
println!("{:?}", double(Some(4)));
}
Output
Some(8)
✅ 9️⃣ ok_or Convert Option → Result
Syntax
opt.ok_or("error")
Program
fn main() {
let val: Option<i32> = None;
let result = val.ok_or("Value missing");
println!("{:?}", result);
}
Output
Err("Value missing")
✅ 🔟 Chained Validation (Production Style)
Syntax
opt
.filter(cond1)
.filter(cond2)
.map(transform)
Program
fn main() {
let amount = Some(500.0);
let result = amount
.filter(|a| *a > 0.0)
.filter(|a| *a <= 1000.0)
.map(|a| a * 1.18);
println!("{:?}", result);
}
Output
Some(590.0)
Project-Level / Real-Time Validation Examples (with output)
11) API: validate LoginForm fields before DB call
#[derive(Debug)]
struct LoginForm {
username: String,
password: String,
}
fn validate_login(form: &LoginForm) -> Option<&'static str> {
match (form.username.trim().is_empty(), form.password.trim().is_empty()) {
(true, _) => Some("username_required"),
(_, true) => Some("password_required"),
_ => None,
}
}
fn main() {
let form = LoginForm { username: "admin".into(), password: "".into() };
match validate_login(&form) {
None => println!("OK: proceed to DB check"),
Some(err_code) => println!("ERR: {}", err_code),
}
}
Output
ERR: password_required
12) Session validation: require user_id and role
fn ensure_session(user_id: Option<i64>, role: Option<String>) -> Option<&'static str> {
match (user_id, role.as_deref()) {
(Some(_), Some("admin" | "viewer")) => None,
(None, _) => Some("missing_user_id"),
(_, None) => Some("missing_role"),
(_, Some(_)) => Some("invalid_role"),
}
}
fn main() {
let user_id = Some(101);
let role = Some("guest".to_string());
match ensure_session(user_id, role) {
None => println!("OK: session valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: invalid_role
13) RBAC authorization check using match
fn can_access(route: &str, role: Option<&str>) -> Option<&'static str> {
match (route, role) {
("/admin", Some("admin")) => None,
("/admin", Some(_)) => Some("forbidden"),
("/admin", None) => Some("unauthorized"),
(_, Some(_)) => None,
(_, None) => Some("unauthorized"),
}
}
fn main() {
let role = Some("viewer");
match can_access("/admin", role) {
None => println!("OK: access granted"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: forbidden
14) Validate pagination query params (page, limit)
fn validate_pagination(page: Option<i64>, limit: Option<i64>) -> Option<&'static str> {
let p = page.and_then(|v| if v >= 1 { Some(v) } else { None });
let l = limit.and_then(|v| if (1..=100).contains(&v) { Some(v) } else { None });
match (p, l) {
(Some(_), Some(_)) => None,
(None, _) => Some("invalid_page"),
(_, None) => Some("invalid_limit"),
}
}
fn main() {
match validate_pagination(Some(0), Some(20)) {
None => println!("OK: pagination valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: invalid_page
15) Validate price and currency for checkout
fn validate_payment(amount: Option<f64>, currency: Option<&str>) -> Option<&'static str> {
let amt = amount.and_then(|a| if a > 0.0 { Some(a) } else { None });
match (amt, currency) {
(Some(_), Some("INR" | "USD")) => None,
(None, _) => Some("invalid_amount"),
(_, None) => Some("currency_required"),
(_, Some(_)) => Some("unsupported_currency"),
}
}
fn main() {
match validate_payment(Some(499.0), Some("EUR")) {
None => println!("OK: payment request valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: unsupported_currency
16) Validate time-range for booking (start < end)
fn validate_time_range(start_min: Option<i32>, end_min: Option<i32>) -> Option<&'static str> {
match (start_min, end_min) {
(Some(s), Some(e)) if s < e => None,
(Some(_), Some(_)) => Some("invalid_range"),
(None, _) => Some("start_required"),
(_, None) => Some("end_required"),
}
}
fn main() {
// 10:00 => 600, 09:30 => 570
match validate_time_range(Some(600), Some(570)) {
None => println!("OK: time range valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: invalid_range
17) Validate API key header (presence + length)
fn validate_api_key(key: Option<&str>) -> Option<&'static str> {
match key {
Some(k) if k.len() >= 20 => None,
Some(_) => Some("api_key_too_short"),
None => Some("api_key_missing"),
}
}
fn main() {
match validate_api_key(Some("short_key")) {
None => println!("OK: api key valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: api_key_too_short
18) Validate JSON payload: required nested field (address.city)
#[derive(Debug)]
struct Address { city: Option<String> }
fn validate_address(addr: Option<Address>) -> Option<&'static str> {
match addr {
Some(a) => match a.city.as_deref() {
Some(c) if !c.trim().is_empty() => None,
_ => Some("city_required"),
},
None => Some("address_required"),
}
}
fn main() {
let addr = Some(Address { city: Some("".into()) });
match validate_address(addr) {
None => println!("OK: address valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: city_required
19) Validate file upload: allow only jpg/png (by extension)
fn validate_file(filename: Option<&str>) -> Option<&'static str> {
match filename {
Some(name) => {
let ext = name.rsplit('.').next();
match ext {
Some("jpg" | "jpeg" | "png") => None,
Some(_) => Some("unsupported_file_type"),
None => Some("missing_extension"),
}
}
None => Some("file_required"),
}
}
fn main() {
match validate_file(Some("avatar.webp")) {
None => println!("OK: file allowed"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: unsupported_file_type
20) Validate DB result: user found + active + password match
#[derive(Clone)]
struct User {
id: i64,
username: String,
password: String,
active: bool,
}
fn validate_login_user(maybe_user: Option<User>, input_pass: &str) -> Option<&'static str> {
match maybe_user {
Some(u) => match (u.active, u.password == input_pass) {
(true, true) => None,
(false, _) => Some("user_inactive"),
(_, false) => Some("wrong_password"),
},
None => Some("user_not_found"),
}
}
fn main() {
let user = Some(User {
id: 1,
username: "admin".into(),
password: "1234".into(),
active: true,
});
match validate_login_user(user, "9999") {
None => println!("OK: login success"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: wrong_password
Multiple conditions inside and_then
let amt = amount.and_then(|a| {
if a > 0.0 && a <= 10_000.0 && a.fract() == 0.0 {
Some(a)
} else {
None
}
});
✔ Conditions:
Must be > 0
Must be <= 10,000
Must not contain decimal value
Using filter() (Cleaner & Recommended)
let amt = amount
.filter(|a| *a > 0.0)
.filter(|a| *a <= 10_000.0)
.filter(|a| a.fract() == 0.0);
Why better?
More readable
Each condition separated
Very production friendly
fn main() {
let amount = Some(499.0);
let curr = Some("USD");
let user_id = Some(101);
let role = Some("admin");
// 1️⃣ Validate amount
let amt = amount
.filter(|a| *a > 0.0)
.filter(|a| *a <= 10_000.0);
// 2️⃣ Validate currency
let currency = curr
.filter(|c| *c == "INR" || *c == "USD");
// 3️⃣ Validate user_id
let uid = user_id
.filter(|id| *id > 0);
// 4️⃣ Validate role
let valid_role = role
.filter(|r| *r == "admin" || *r == "viewer");
// 5️⃣ Match all 4 together
match (amt, currency, uid, valid_role) {
(Some(a), Some(c), Some(id), Some(r)) => {
println!("OK: amount={} currency={} user_id={} role={}", a, c, id, r)
}
(None, _, _, _) => println!("ERR: invalid amount"),
(_, None, _, _) => println!("ERR: invalid currency"),
(_, _, None, _) => println!("ERR: invalid user_id"),
(_, _, _, None) => println!("ERR: invalid role"),
}
}
✅ Output (Valid Case)
OK: amount=499 currency=USD user_id=101 role=admin
Using match with guard (Very Clean Rust Way)
let amt = match amount {
Some(a) if a > 0.0 && a <= 10_000.0 && a.fract() == 0.0 => Some(a),
_ => None,
};
This is extremely readable and used often in real projects.
✅ 4.
Return different error messages per condition (Better for APIs)
If you want specific error reasons:
fn validate_amount(amount: Option<f64>) -> Option<&'static str> {
match amount {
None => Some("amount_required"),
Some(a) if a <= 0.0 => Some("amount_must_be_positive"),
Some(a) if a > 10_000.0 => Some("amount_too_large"),
Some(a) if a.fract() != 0.0 => Some("no_decimal_allowed"),
Some(_) => None,
}
}
Output
match validate_amount(Some(20000.0)) {
None => println!("OK"),
Some(e) => println!("ERR: {}", e),
}
ERR: amount_too_large
This is real-world production style.
✅ 5.
Full Updated Payment Example (Multiple Conditions + Currency)
fn validate_payment(amount: Option<f64>, currency: Option<&str>) -> Option<&'static str> {
match amount {
None => return Some("amount_required"),
Some(a) if a <= 0.0 => return Some("amount_must_be_positive"),
Some(a) if a > 10_000.0 => return Some("amount_exceeds_limit"),
_ => {}
}
match currency {
None => Some("currency_required"),
Some("INR" | "USD") => None,
Some(_) => Some("unsupported_currency"),
}
}
fn main() {
match validate_payment(Some(499.0), Some("EUR")) {
None => println!("OK: payment request valid"),
Some(e) => println!("ERR: {}", e),
}
}
Output
ERR: unsupported_currency
User Registration Validation (username + email + age)
fn main() {
let username = Some("ashwani");
let email = Some("test@gmail.com");
let age = Some(22);
let valid_username = username.filter(|u| u.len() >= 3);
let valid_email = email.filter(|e| e.contains('@') && e.contains('.'));
let valid_age = age.filter(|a| *a >= 18);
match (valid_username, valid_email, valid_age) {
(Some(u), Some(e), Some(a)) =>
println!("OK: {} {} {}", u, e, a),
(None, _, _) => println!("ERR: invalid username"),
(_, None, _) => println!("ERR: invalid email"),
(_, _, None) => println!("ERR: age must be 18+"),
}
}
Output
OK: ashwani test@gmail.com 22
✅ 2️⃣
Product Order Validation (price + quantity + stock)
fn main() {
let price = Some(1200.0);
let quantity = Some(2);
let stock = Some(5);
let valid_price = price.filter(|p| *p > 0.0);
let valid_quantity = quantity.filter(|q| *q > 0);
let valid_stock = match (quantity, stock) {
(Some(q), Some(s)) if q <= s => Some(s),
_ => None,
};
match (valid_price, valid_quantity, valid_stock) {
(Some(p), Some(q), Some(_)) =>
println!("OK: order placed price={} qty={}", p, q),
(None, _, _) => println!("ERR: invalid price"),
(_, None, _) => println!("ERR: invalid quantity"),
(_, _, None) => println!("ERR: not enough stock"),
}
}
Output
OK: order placed price=1200 qty=2
✅ 3️⃣
Login Validation (username + password + role)
fn main() {
let username = Some("admin");
let password = Some("secret123");
let role = Some("admin");
let valid_user = username.filter(|u| !u.is_empty());
let valid_pass = password.filter(|p| p.len() >= 8);
let valid_role = role.filter(|r| *r == "admin" || *r == "viewer");
match (valid_user, valid_pass, valid_role) {
(Some(u), Some(_), Some(r)) =>
println!("OK: login success {} {}", u, r),
(None, _, _) => println!("ERR: username required"),
(_, None, _) => println!("ERR: password too short"),
(_, _, None) => println!("ERR: invalid role"),
}
}
Output
OK: login success admin admin
✅ 4️⃣
Booking Validation (start_time + end_time + seats)
fn main() {
let start_time = Some(600); // 10:00 AM
let end_time = Some(900); // 3:00 PM
let seats = Some(3);
let valid_time = match (start_time, end_time) {
(Some(s), Some(e)) if s < e => Some((s, e)),
_ => None,
};
let valid_seats = seats.filter(|s| *s > 0 && *s <= 5);
match (valid_time, valid_seats) {
(Some((s, e)), Some(seat)) =>
println!("OK: booking {}-{} seats={}", s, e, seat),
(None, _) => println!("ERR: invalid time range"),
(_, None) => println!("ERR: invalid seats"),
}
}
Output
OK: booking 600-900 seats=3
✅ 5️⃣
Payment Validation (amount + currency + user_id + status)
fn main() {
let amount = Some(499.0);
let currency = Some("USD");
let user_id = Some(101);
let status = Some("active");
let valid_amount = amount.filter(|a| *a > 0.0 && *a <= 10_000.0);
let valid_currency = currency.filter(|c| *c == "INR" || *c == "USD");
let valid_user = user_id.filter(|id| *id > 0);
let valid_status = status.filter(|s| *s == "active");
match (valid_amount, valid_currency, valid_user, valid_status) {
(Some(a), Some(c), Some(id), Some(_)) =>
println!("OK: payment {} {} user={}", a, c, id),
(None, _, _, _) => println!("ERR: invalid amount"),
(_, None, _, _) => println!("ERR: invalid currency"),
(_, _, None, _) => println!("ERR: invalid user"),
(_, _, _, None) => println!("ERR: account not active"),
}
}
Output
OK: payment 499 USD user=101
Top comments (0)