Skip to main content

Module validators

Module validators 

Source
Expand description

Standalone validators — validate_email, validate_url, validate_slug, validate_min_length / validate_max_length, validate_min_value / validate_max_value. See validators. Standalone validators.

Lightweight check functions. Each returns Result<(), ValidationError> so they compose with ? inside Form::clean() or any other input-validation flow.

ⓘ
use rustango::validators::{validate_email, validate_url, validate_slug};

pub fn clean_contact(email: &str, website: &str, handle: &str) -> Result<(), ValidationError> {
    validate_email(email)?;
    validate_url(website)?;
    validate_slug(handle)?;
    Ok(())
}

§Scope

Hand-rolled checks (no regex crate dependency) — fast, allocation-free, and cover the 99% case. The character classes are the ones a typical web form needs:

  • validate_email — basic shape check (local-part @ domain . tld). NOT RFC 5322. Catches typos like missing @ or empty parts.
  • validate_url — accepts http:// / https:// schemes with a non-empty host. Optional port + path + query.
  • validate_slug — [a-zA-Z0-9_-]+, ASCII only.
  • validate_unicode_slug — letters of any script + digits + _ + -.
  • validate_prohibit_null_characters — reject strings containing NUL (\0), at form-input boundaries, to block null-byte injection.
  • validate_min_length / validate_max_length — string char count.
  • validate_min_value / validate_max_value — i64 numeric bounds.
  • validate_min_value_f64 / validate_max_value_f64 — float bounds, for prices / measurements / scientific values that don’t fit i64.
  • validate_integer — parses as i64.
  • validate_decimal — max_digits + decimal_places bounds.
  • validate_file_size_max / validate_file_mime_type — file-upload size + MIME allowlist checks.
  • validate_step_value — n == offset + k*step for non-negative integer k.
  • validate_ipv4_address / validate_ipv6_address — dotted-quad / colon-hex address shape via std::net::Ipv4Addr / Ipv6Addr.
  • validate_comma_separated_integer_list — "1,2,3".
  • validate_email_list — comma-separated list of email addresses, one per “CC” field entry.
  • validate_phone_e164 — E.164 international phone format (+ followed by 1–15 digits).
  • validate_hex_color — #rgb / #rrggbb / #rrggbbaa / #rgba web-color hex codes. For color-picker form fields.
  • validate_uuid — RFC 4122 UUID string format. Useful for handler argument validation when a path/query carries a UUID you want to validate before hitting the DB.
  • validate_iso_date — ISO 8601 YYYY-MM-DD date.
  • validate_iso_time — ISO 8601 HH:MM:SS time (optional fractional seconds).
  • validate_iso_datetime — RFC 3339 / ISO 8601 datetime with timezone offset (...Z or +HH:MM).
  • validate_alphanumeric — [a-zA-Z0-9]+ ASCII only.
  • validate_numeric — [0-9]+ ASCII digits only.
  • validate_alpha — [a-zA-Z]+ ASCII letters only.
  • validate_creditcard_luhn — Luhn checksum on a credit card PAN string. Catches typos before hitting the PCI processor; does NOT verify the card is real / not expired / has funds.
  • validate_isbn — ISBN-10 or ISBN-13 checksum (auto-detects which form by digit count).
  • validate_hostname — RFC 1123 hostname format. Each dot-separated label 1–63 chars, letters/digits/hyphens, no leading or trailing hyphen, total length ≤ 253.
  • validate_iban — ISO 13616 IBAN mod-97 checksum (catches typos in bank account fields).
  • validate_mac_address — EUI-48 MAC address (6 hex pairs separated by : or -).
  • validate_base64 — standard base64 ([A-Za-z0-9+/] + optional = padding).
  • validate_base64_urlsafe — URL-safe base64 ([A-Za-z0-9_-]).
  • validate_jwt_shape — three dot-separated URL-safe base64 segments. Shape check only, NO signature verification.
  • validate_semver — semantic version 2.0.0 (MAJOR.MINOR.PATCH with optional -pre.release and +build suffixes).
  • validate_country_code — ISO 3166-1 alpha-2 country code (2 uppercase letters). Format-only; doesn’t check the code exists.
  • validate_currency_code — ISO 4217 currency code (3 uppercase letters). Format-only.
  • validate_language_tag — BCP 47 light: lang[-region] (e.g. en, en-US, fr-CA, zh-Hans).
  • validate_postal_code_us — US ZIP code in 12345 or 12345-6789 (ZIP+4) form.
  • validate_postal_code_ca — Canadian postal code in A1A 1A1 form (uppercase, single space).
  • validate_postal_code_uk — UK postcode (SW1A 1AA shape; loose check on the well-formed cases).

What’s NOT here (yet):

  • Locale-sensitive numeric formats.
  • IDN / punycode email + URL support (the basic check accepts ASCII; non-ASCII domains are valid per RFC but the basic shape rejects them — file a follow-up if you actually need IDN forms).

Structs§

ValidationError
One validation failure.

Functions§

clean_ipv6_address
Normalize an IPv6 address into the canonical RFC 5952 compressed form (lowercase hex, longest zero-run replaced with ::, leading zeros dropped per group).
int_list_validator
Parameterized variant of validate_comma_separated_integer_list.
is_alpha
true when s would pass validate_alpha.
is_alphanumeric
true when s would pass validate_alphanumeric.
is_base64
true when s would pass validate_base64.
is_base64_urlsafe
true when s would pass validate_base64_urlsafe.
is_country_code
true when s would pass validate_country_code (ISO 3166-1 alpha-2). Boolean form for filter chains; the Result form remains the right call when the message matters.
is_creditcard_luhn
true when s would pass validate_creditcard_luhn.
is_currency_code
true when s would pass validate_currency_code (ISO 4217 alpha-3). Boolean form for filter chains.
is_email
Boolean form of validate_email. Useful in if guards where the caller doesn’t need the error message.
is_email_with_name
true when s would pass validate_email_with_name.
is_filepath
true when s would pass validate_filepath — POSIX-shape path with no embedded NUL / control chars. Boolean form for filter chains.
is_hex_color
Boolean form of validate_hex_color.
is_hostname
true when s would pass validate_hostname.
is_iban
true when s would pass validate_iban.
is_ip_address
true when s would pass validate_ip_address — an alias of is_ipv46_address. Boolean form for filter chains.
is_ipv4_address
true when s would pass validate_ipv4_address (dotted-quad IPv4). Boolean form for filter chains.
is_ipv6_address
true when s would pass validate_ipv6_address (RFC 4291 IPv6, condensed or full). Boolean form for filter chains.
is_ipv46_address
true when s would pass validate_ipv46_address (accepts either IPv4 or IPv6). Boolean form for filter chains.
is_isbn
true when s would pass validate_isbn.
is_iso_date
true when s would pass validate_iso_date.
is_iso_datetime
true when s would pass validate_iso_datetime.
is_iso_time
true when s would pass validate_iso_time.
is_jwt_shape
true when s would pass validate_jwt_shape.
is_language_tag
true when s would pass validate_language_tag (BCP 47 language tag). Boolean form for filter chains.
is_mac_address
true when s would pass validate_mac_address.
is_numeric
true when s would pass validate_numeric.
is_phone_e164
Boolean form of validate_phone_e164.
is_postal_code_ca
true when s would pass validate_postal_code_ca (A1A 1A1 / A1A1A1). Boolean form for filter chains.
is_postal_code_uk
true when s would pass validate_postal_code_uk (UK postcode shape). Boolean form for filter chains.
is_postal_code_us
true when s would pass validate_postal_code_us (5-digit or 9-digit ZIP). Boolean form for filter chains.
is_semver
true when s would pass validate_semver.
is_slug
Boolean form of validate_slug.
is_unicode_slug
Boolean form of validate_unicode_slug.
is_url
Boolean form of validate_url.
is_uuid
Boolean form of validate_uuid.
validate_alpha
Reject any input that contains characters outside [a-zA-Z]. Non-empty input required. ASCII only.
validate_alphanumeric
Reject any input that contains characters outside [a-zA-Z0-9]. Non-empty input required. ASCII only — for the Unicode-aware variant use validate_unicode_slug (which adds _ / - to letters/digits).
validate_base64
Validate that s is a well-formed standard base64 string: characters from [A-Za-z0-9+/], length a multiple of 4 after optional = padding (at most two trailing =).
validate_base64_urlsafe
Validate that s is a well-formed URL-safe base64 string: characters from [A-Za-z0-9_-], length a multiple of 4 after optional = padding (or, by RFC 4648 convention, padding may be omitted in URL-safe encoding — we accept either).
validate_comma_separated_integer_list
Validate that s is a comma-separated list of integers ("1,2,3"). Empty string is rejected — use Option<String> upstream if the field is optional.
validate_country_code
Validate an ISO 3166-1 alpha-2 country code: exactly 2 uppercase ASCII letters (US, GB, DE, JP, …). Format-only — does NOT check that the code corresponds to a real country (that would need an embedded list of 249 codes maintained against every ISO update).
validate_creditcard_luhn
Verify the Luhn checksum on a credit-card-shape Primary Account Number (PAN). Strips spaces and hyphens (the typical human-typed shape), then checks that:
validate_currency_code
Validate an ISO 4217 currency code: exactly 3 uppercase ASCII letters (USD, EUR, GBP, JPY, …). Format-only — does NOT check that the code corresponds to a circulating currency.
validate_decimal
Validate a decimal-number string: at most max_digits total digits (excluding sign + decimal point), and at most decimal_places digits after the point.
validate_email
Validate that s looks like an email address.
validate_email_list
Validate a comma-separated list of email addresses (e.g. a “CC” field that takes multiple recipients). Each entry must pass validate_email; surrounding whitespace per entry is tolerated.
validate_email_with_name
Accepts both a bare email (user@host.tld) and the RFC 5322 display-name form ("Display Name" <user@host.tld> or Display Name <user@host.tld>).
validate_file_extension
Reject filenames whose extension (case-insensitive) isn’t on the allowlist. The extension is everything after the LAST . in the filename, so archive.tar.gz has extension gz. allowed_extensions entries are compared lowercase; pass them without the leading dot (["jpg", "png"], not [".jpg"]).
validate_file_mime_type
MIME-type allowlist — reject uploads whose Content-Type (or per-part media-type for multipart forms) isn’t in allowed_mimetypes. Comparison is case-insensitive on the type/subtype portion and ignores any trailing ; charset=... parameters.
validate_file_size_max
File-size cap — reject uploads whose byte length exceeds max_bytes. Pair with uploads::save_uploads (which streams and caps at the transport layer) when the form-level check should produce a field error instead of a 413 response.
validate_filepath
Validate that s looks like a safe filesystem path string: non-empty, no NUL bytes, no .. parent-directory segments (path traversal). This is the structural half only — it does NOT touch the filesystem, so the caller still has to verify existence, readability and sandbox membership.
validate_hex_color
Validate a web-color hex code: #rgb, #rrggbb, #rgba, or #rrggbbaa. The # prefix is required; hex digits are case-insensitive. Anything else (named colors, rgb() / hsl() functions, hex without #) is rejected.
validate_hostname
Validate an RFC 1123 hostname: dot-separated labels, each label 1–63 chars containing only ASCII letters / digits / hyphens, no leading or trailing hyphen on any label, total length ≤ 253. Empty string is rejected.
validate_iban
Validate an ISO 13616 IBAN (International Bank Account Number) via the mod-97 check. Strips spaces (the typical printed “GB82 WEST 1234 5698 7654 32” shape) before validating.
validate_image_dimensions
Bounded width/height check for an image already decoded by the caller. Each bound is optional — pass None to skip that side.
validate_image_file_extension
Convenience around validate_file_extension that allows the usual image extensions: bmp / dib / gif / tif / tiff / jfif / jpe / jpg / jpeg / pbm / pgm / ppm / pnm / png / apng / blp / bufr / cur / pcx / dcx / dds / ps / eps / fit / fits / fli / flc / ftc / ftu / gbr / gif / grib / h5 / hdf / jp2 / j2k / jpc / jpf / jpx / j2c / icns / ico / im / iim / mic / mpo / msp / palm / pcd / pdf / pxr / psd / bw / rgb / rgba / sgi / ras / tga / icb / vda / vst / webp / wmf / emf / xbm / xpm.
validate_integer
Validate that s parses as a signed 64-bit integer. Leading and trailing whitespace is rejected.
validate_ip_address
Validate that s parses as either an IPv4 or IPv6 address.
validate_ipv4_address
Validate that s parses as an IPv4 address (dotted-quad). Uses std::net::Ipv4Addr::from_str so the parse rules match the rest of the standard library.
validate_ipv6_address
Validate that s parses as an IPv6 address. Uses std::net::Ipv6Addr::from_str.
validate_ipv46_address
Accept EITHER an IPv4 or an IPv6 address — the check for a field that takes both families.
validate_isbn
Verify the checksum on an ISBN-10 or ISBN-13 string. Strips spaces and hyphens (the typical printed shape), then dispatches on digit count:
validate_iso_date
Validate an ISO 8601 calendar date in YYYY-MM-DD format. Rejects shorter / longer strings and out-of-range months / days (Feb 30, month 13, day 0 etc.) via chrono’s NaiveDate::parse_from_str.
validate_iso_datetime
Validate an RFC 3339 / ISO 8601 datetime with timezone offset (2026-01-15T14:30:00Z or 2026-01-15T14:30:00+02:00). The timezone is REQUIRED — naive datetimes (no offset) are rejected because mixing local-time and UTC values without a marker is a classic data-corruption vector.
validate_iso_time
Validate an ISO 8601 wall-clock time in HH:MM:SS format, optionally with fractional seconds (HH:MM:SS.sss). Rejects out-of-range hours / minutes / seconds.
validate_jwt_shape
Validate that s looks like a JWT: three URL-safe base64 segments separated by ., each non-empty.
validate_language_tag
Validate a BCP 47-shape language tag in its most common forms:
validate_mac_address
Validate an EUI-48 MAC address: six pairs of hex digits separated by : or -. Case-insensitive. The separator must be consistent across the string (no mix-and-match between : and -).
validate_max_length
Reject strings longer than max characters.
validate_max_value
Reject integers above max.
validate_max_value_f64
Reject floats above max. Float variant of validate_max_value. NaN is rejected.
validate_min_length
Reject strings shorter than min characters — Unicode code points, not bytes.
validate_min_value
Reject integers below min.
validate_min_value_f64
Reject floats below min. Float variant of validate_min_value for prices, measurements, scientific values that don’t fit i64. NaN is rejected.
validate_numeric
Reject any input that contains characters outside [0-9]. Non-empty input required. No sign, no decimal point, no underscores — use validate_integer for those.
validate_phone_e164
Validate an E.164 international phone number: a + followed by 1 to 15 ASCII digits, no other characters. This is the format every modern phone API (Twilio, AWS SNS, Vonage) expects.
validate_postal_code_ca
Validate a Canadian postal code: 6 characters in the alternating letter-digit-letter-space-digit-letter-digit pattern (A1A 1A1). Letters must be uppercase ASCII.
validate_postal_code_uk
Validate a UK postcode in the canonical OUTWARD INWARD shape: 1-2 outward characters + space + 3 inward characters.
validate_postal_code_us
Validate a US ZIP code: either 5 digits (94110) or the ZIP+4 form 12345-6789. No other separators or formats are accepted.
validate_prohibit_null_characters
Reject strings containing NUL (\0). Null bytes inside user input are a known injection vector against C-string-aware downstream systems (database drivers, file paths, syscalls) and almost never represent legitimate user intent, so it is worth running on every free-text field.
validate_semver
Validate a Semantic Versioning 2.0.0 version string: MAJOR.MINOR.PATCH with optional -pre.release and +build.metadata suffixes.
validate_slug
Validate that s is a slug: [a-zA-Z0-9_-]+, no other characters, must be non-empty.
validate_step_value
Validate that n equals offset + k * step for some non-negative integer k. Enforces HTML5 <input type=number step="…"> semantics on the server side.
validate_unicode_slug
Validate a unicode-aware slug. Allows any Unicode alphanumeric character plus _ and -. Use this instead of validate_slug when slugs come from non-Latin titles.
validate_url
Validate that s looks like an http:// / https:// URL.
validate_uuid
Validate a UUID string in any of the formats uuid::Uuid::parse_str accepts (hyphenated, simple, URN, or braced). Backs onto the uuid crate so the accepted shapes match the rest of rustango.