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— acceptshttp:///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 fiti64.validate_integer— parses asi64.validate_decimal—max_digits+decimal_placesbounds.validate_file_size_max/validate_file_mime_type— file-upload size + MIME allowlist checks.validate_step_value—n == offset + k*stepfor non-negative integerk.validate_ipv4_address/validate_ipv6_address— dotted-quad / colon-hex address shape viastd::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/#rgbaweb-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 8601YYYY-MM-DDdate.validate_iso_time— ISO 8601HH:MM:SStime (optional fractional seconds).validate_iso_datetime— RFC 3339 / ISO 8601 datetime with timezone offset (...Zor+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.PATCHwith optional-pre.releaseand+buildsuffixes).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 in12345or12345-6789(ZIP+4) form.validate_postal_code_ca— Canadian postal code inA1A 1A1form (uppercase, single space).validate_postal_code_uk— UK postcode (SW1A 1AAshape; 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§
- Validation
Error - 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 truewhenswould passvalidate_alpha.- is_
alphanumeric truewhenswould passvalidate_alphanumeric.- is_
base64 truewhenswould passvalidate_base64.- is_
base64_ urlsafe truewhenswould passvalidate_base64_urlsafe.- is_
country_ code truewhenswould passvalidate_country_code(ISO 3166-1 alpha-2). Boolean form for filter chains; theResultform remains the right call when the message matters.- is_
creditcard_ luhn truewhenswould passvalidate_creditcard_luhn.- is_
currency_ code truewhenswould passvalidate_currency_code(ISO 4217 alpha-3). Boolean form for filter chains.- is_
email - Boolean form of
validate_email. Useful inifguards where the caller doesn’t need the error message. - is_
email_ with_ name truewhenswould passvalidate_email_with_name.- is_
filepath truewhenswould passvalidate_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 truewhenswould passvalidate_hostname.- is_iban
truewhenswould passvalidate_iban.- is_
ip_ address truewhenswould passvalidate_ip_address— an alias ofis_ipv46_address. Boolean form for filter chains.- is_
ipv4_ address truewhenswould passvalidate_ipv4_address(dotted-quad IPv4). Boolean form for filter chains.- is_
ipv6_ address truewhenswould passvalidate_ipv6_address(RFC 4291 IPv6, condensed or full). Boolean form for filter chains.- is_
ipv46_ address truewhenswould passvalidate_ipv46_address(accepts either IPv4 or IPv6). Boolean form for filter chains.- is_isbn
truewhenswould passvalidate_isbn.- is_
iso_ date truewhenswould passvalidate_iso_date.- is_
iso_ datetime truewhenswould passvalidate_iso_datetime.- is_
iso_ time truewhenswould passvalidate_iso_time.- is_
jwt_ shape truewhenswould passvalidate_jwt_shape.- is_
language_ tag truewhenswould passvalidate_language_tag(BCP 47 language tag). Boolean form for filter chains.- is_
mac_ address truewhenswould passvalidate_mac_address.- is_
numeric truewhenswould passvalidate_numeric.- is_
phone_ e164 - Boolean form of
validate_phone_e164. - is_
postal_ code_ ca truewhenswould passvalidate_postal_code_ca(A1A 1A1/A1A1A1). Boolean form for filter chains.- is_
postal_ code_ uk truewhenswould passvalidate_postal_code_uk(UK postcode shape). Boolean form for filter chains.- is_
postal_ code_ us truewhenswould passvalidate_postal_code_us(5-digit or 9-digit ZIP). Boolean form for filter chains.- is_
semver truewhenswould passvalidate_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 usevalidate_unicode_slug(which adds_/-to letters/digits). - validate_
base64 - Validate that
sis 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
sis 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
sis a comma-separated list of integers ("1,2,3"). Empty string is rejected — useOption<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_digitstotal digits (excluding sign + decimal point), and at mostdecimal_placesdigits after the point. - validate_
email - Validate that
slooks 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>orDisplay 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, soarchive.tar.gzhas extensiongz.allowed_extensionsentries 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 inallowed_mimetypes. Comparison is case-insensitive on thetype/subtypeportion and ignores any trailing; charset=...parameters. - validate_
file_ size_ max - File-size cap — reject uploads whose byte length exceeds
max_bytes. Pair withuploads::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
slooks 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
Noneto skip that side. - validate_
image_ file_ extension - Convenience around
validate_file_extensionthat 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
sparses as a signed 64-bit integer. Leading and trailing whitespace is rejected. - validate_
ip_ address - Validate that
sparses as either an IPv4 or IPv6 address. - validate_
ipv4_ address - Validate that
sparses as an IPv4 address (dotted-quad). Usesstd::net::Ipv4Addr::from_strso the parse rules match the rest of the standard library. - validate_
ipv6_ address - Validate that
sparses as an IPv6 address. Usesstd::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-DDformat. Rejects shorter / longer strings and out-of-range months / days (Feb 30, month 13, day 0 etc.) via chrono’sNaiveDate::parse_from_str. - validate_
iso_ datetime - Validate an RFC 3339 / ISO 8601 datetime with timezone offset
(
2026-01-15T14:30:00Zor2026-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:SSformat, optionally with fractional seconds (HH:MM:SS.sss). Rejects out-of-range hours / minutes / seconds. - validate_
jwt_ shape - Validate that
slooks 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
maxcharacters. - validate_
max_ value - Reject integers above
max. - validate_
max_ value_ f64 - Reject floats above
max. Float variant ofvalidate_max_value. NaN is rejected. - validate_
min_ length - Reject strings shorter than
mincharacters — Unicode code points, not bytes. - validate_
min_ value - Reject integers below
min. - validate_
min_ value_ f64 - Reject floats below
min. Float variant ofvalidate_min_valuefor prices, measurements, scientific values that don’t fiti64. 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 — usevalidate_integerfor 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 INWARDshape: 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 form12345-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.PATCHwith optional-pre.releaseand+build.metadatasuffixes. - validate_
slug - Validate that
sis a slug:[a-zA-Z0-9_-]+, no other characters, must be non-empty. - validate_
step_ value - Validate that
nequalsoffset + k * stepfor some non-negative integerk. 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 ofvalidate_slugwhen slugs come from non-Latin titles. - validate_
url - Validate that
slooks like anhttp:///https://URL. - validate_
uuid - Validate a UUID string in any of the formats
uuid::Uuid::parse_straccepts (hyphenated, simple, URN, or braced). Backs onto theuuidcrate so the accepted shapes match the rest of rustango.