#Validation
Status: standard library specification draft.
This chapter defines std.validate: value validation after a reader has
constructed a typed value. Validation observes the value without coercion or
normalization. It reports structural paths so JSON, HTTP, command-line, and
environment callers can choose their own field spellings.
#Values And Errors
| Rule | Item | Meaning |
|---|---|---|
std-validate.problem.declProblem |
pub struct Problem { pub code: string, pub message: string } |
one stable code and explanation |
std-validate.path.declPathStep |
Field(member: Member), Index(value: usize), Key(name: string) |
one structural path step |
std-validate.violation.declViolation |
pub struct Violation { pub path: List[PathStep], pub problem: Problem } |
one problem at one path |
std-validate.error.declValidationError |
Invalid(issues: List[Violation], truncated: bool), Definition(path: List[PathStep], reason: string) |
invalid data or an invalid rule definition |
- std-validate.violation.display-with
Violation.display_with(name: fn(&PathStep) -> string)begins with$and appendsname(step)for each path step in order. AFieldsnapshots the originalMembermetadata, including its facts. The function borrows each step so a reader can render an external field name without consuming the stored path. - std-validate.error.issues
ValidationError.issues(self) -> List[Violation]consumes the error and returns the issues ofInvalid, in visit order, or an empty list forDefinition. A caller that inspects the result more than once binds that returned list once. - std-validate.error.display
Invaliddisplays one source-namedpath: messageper line and, whentruncatedis true, a final limit line.Definitiondisplaysinvalid validation rule:followed by its reason.
#Validate
use std.validate.{Validate, ValidationContext}
impl Validate for Account by Structure:
name = [length(1, 80)]
fn record(&self, context: &mut ValidationContext) -> void:
if self.password != self.confirmation:
context.reject("confirmation", "passwords must match")- std-validate.trait.decl
std.validatedeclarespub trait Validatewithcollect, the defaulted completed-value callbackrecord, andvalidated(self, max_errors: usize = 64) -> Result[Self, ValidationError]. - std-validate.trait.dispatch
Validatedefault-defineslength_of,text_of,partial_cmp_of,equal_to,unique_items, andpath_nameas unavailable queries. Standard implementations override the operations they support. Its defaultapply_attachedreads the member's exact rule facts through theFieldhandle; the optional implementation instead reads facts typed for its payload. - std-validate.validated.same-value
validatedreturns the same value inOkwhen no rule rejects it. It performs no conversion, normalization, or promise about a later mutation. - std-validate.validated.positive-cap
max_errorsmust be positive. Zero returnsDefinition. A positive cap retains at most that many issues and stops starting later checks once it is reached. - std-validate.validated.truncated
Invalid.truncatedis true exactly when validation skipped a later check because the cap was already reached. A record callback that has started completes normally; an issue it reports beyond the cap is not retained. - std-validate.context.reject
ValidationContext.reject(code, message)reports aProblemat the callback's current structural path. A completed-record callback runs at that record's root. - std-validate.derive.structure
impl Validate for T by Structurevisits the active variant's included members in declaration order. It applies their validation facts instd-validate.rule.builtin-order, recursively validates each member, and then runs that nested value'srecordcallback. - std-validate.container.list
List[T]implementsValidatewhenTdoes, visiting its elements in index order underIndexsteps. - std-validate.container.map
Map[K, V]implementsValidatewhen its key and value types do and the key also implementsEq & Hash. It visits entries in map order under aKeystep, using the key text where available and<key>otherwise. - std-validate.container.option
T?implementsValidatewhenTdoes..Some(value)recursively validatesvalue;.Noneperforms no payload check. A member fact inferred forTbyannot.typed-fact.check.optional-payloadapplies to the.Somepayload and is skipped for.None. - std-validate.container.leavesStrings, characters, booleans, and number types implement
Validateas leaves.
#Rule Facts
Every built-in rule is a data-only typed fact on a field. Its target parameter
is unbounded on the fact declaration; the builder carries the semantic bound.
The message named argument replaces the rule's default message without
changing its code. Check[F] is the sole rule fact that stores executable
logic.
| Rule | Builder and fact | Rejection |
|---|---|---|
std-validate.rule.rangerange |
range[F < PartialOrd](low: F, high: F, message: string? = .None) -> Range[F] |
outside the inclusive bounds; code range |
std-validate.rule.minmin |
min[F < PartialOrd](bound: F, message: string? = .None) -> Min[F] |
below the inclusive bound; code min |
std-validate.rule.maxmax |
max[F < PartialOrd](bound: F, message: string? = .None) -> Max[F] |
above the inclusive bound; code max |
std-validate.rule.lengthlength |
length[F < HasLength](minimum: usize, maximum: usize, message: string? = .None) -> Length[F] |
outside the inclusive length range; code length |
std-validate.rule.min-lengthmin_length |
min_length[F < HasLength](minimum: usize, message: string? = .None) -> MinLength[F] |
shorter than the minimum; code min-length |
std-validate.rule.max-lengthmax_length |
max_length[F < HasLength](maximum: usize, message: string? = .None) -> MaxLength[F] |
longer than the maximum; code max-length |
std-validate.rule.byte-lengthbyte_length |
byte_length(minimum: usize, maximum: usize, message: string? = .None) -> ByteLength[string] |
UTF-8 byte length outside the inclusive range; code byte-length |
std-validate.rule.patternpattern |
pattern(source: string, message: string? = .None) -> Pattern[string] |
the regex finds no match; code pattern |
std-validate.rule.emailemail |
email(message: string? = .None) -> Email[string] |
not a valid address; code email |
std-validate.rule.urlurl |
url(message: string? = .None) -> Url[string] |
not an accepted absolute URL; code url |
std-validate.rule.uuiduuid |
uuid(message: string? = .None) -> Uuid[string] |
not 8-4-4-4-12 hexadecimal UUID text; code uuid |
std-validate.rule.one-ofone_of |
one_of[F < Eq](values: List[F], message: string? = .None) -> OneOf[F] |
unequal to every listed value; code one-of |
std-validate.rule.uniqueunique |
unique[F < Eq & Hash & Validate](message: string? = .None) -> Unique[List[F]] |
two list elements compare equal; code unique |
std-validate.rule.check.capture-freecheck |
check[F, G < 'static & Fn(&F) -> Result[void, Problem]](test: G, message: string? = .None) -> Check[F]; stores a concrete fn wrapper around test |
the callback's Err(problem); its code and message, with message replacing only the message |
- std-validate.rule.declarationsThe table's fact types are structs parameterized by
F. Each carries@annotate::[F](.Field). - std-validate.rule.builtin-orderDistinct rule facts on one member run in the table's declaration order. Thus
Check[F]runs after every built-in rule. The ordinary duplicate-fact rule rejects two facts of the same concrete fact type. - std-validate.rule.definitionA reversed range, reversed length range, or invalid regular expression returns
Definitionat the current path. The same applies when the required operation is unavailable. These failures do not reject the value. - std-validate.rule.optionalEach rule builder used on a
T?member keeps its payload fact type. It checks.SomeasTand skips.None, includingCheck[T].
#Length And Text Grammars
- std-validate.length.trait
std.validatedeclarespub trait HasLength { fn length(&self) -> usize }. Strings count Unicode scalar values, lists count elements, and maps count entries. An optional delegates to its payload and gives zero for.None. - std-validate.length.bytes
byte_lengthcounts the UTF-8 bytes of a string, separately from scalar length. - std-validate.pattern.search
patterncompilessourcewithstd.regex.Regex::newand usesis_match, so anchors are required for a whole-text constraint. - std-validate.email.whatwg
emailaccepts exactly the WHATWG HTML valid e-mail address grammar: an ASCII atom local part and DNS-style ASCII domain. Plus addressing and a one-label domain are accepted; quoted local parts, spaces, IP-literal domains, and IDN conversion are not. - std-validate.url.absolute
urlaccepts exactly the absolute HTTP or HTTPS URL text thatstd.http.Url.parseaccepts. A relative URL is rejected. - std-validate.uuid.syntax
uuidaccepts five hexadecimal groups of lengths 8, 4, 4, 4, and 12 separated by hyphens, case-insensitively. It does not restrict version or variant bits.
#Reader Names
- std-validate.reader.namesValidation stores source
Memberidentities, not JSON, CLI, form, query, or environment spellings. A caller renders those spellings withViolation.display_with; opaque callers use the source-name display ofValidationError. - std-validate.reader.boundaryReaders retain their existing decoding and parse errors. Applications call
.validated()after a successful JSON, HTTP body, CLI, environment, form, or query read; validation errors are not decoding errors.