validate - declarative data validation
Import with import "validate.j" as validate;. Validate a map of string to string (a form body, a query string, a config) against a rule set and get a structured failure list back, instead of ad-hoc per-field if checks scattered through a handler. Rules compose as value-semantic descriptors built by the validate.required / integer / min / email / ... family. Pure Jennifer over regex + uri + time + password + convert + lists + strings + maps, so it runs on both binaries.
use io;
import "validate.j" as validate;
def form as map of string to string init {"email": "ann@example.com", "age": "abc", "role": "root"};
def rules as map of string to list of validate.Rule init {
"email": [validate.required(), validate.email()],
"age": [validate.integer(), validate.min(0.0), validate.max(150.0)],
"role": [validate.oneOf(["reader", "author", "admin"])]
};
def errs as list of validate.Failure init validate.check($form, $rules);
if (len($errs) > 0) {
for (def m in validate.messages($errs)) { io.printf("%s\n", $m); }
}Runnable: examples/modules/validate_demo.j
The model
A rule set is a map of string to list of Rule: each field maps to the rules it must satisfy, in order. validate.check(data, rules) returns a list of Failure ({field, rule, param, message}) - empty means valid; validate.ok(data, rules) is the bool short-circuit. checkValue checks a single value, and ensure / ensureValue throw instead of returning failures (see One value, and throwing).
Values are strings - the shape web.bodyForm, a query string, or dotenv produce. A type rule (integer / number / boolean) checks the string parses; min / max parse then compare; minLen / maxLen measure the string (in runes).
Two conventions to know:
- Only fields named in the rule set are checked. Extra keys in
dataare ignored. - An absent or blank field passes every rule except
required. So an optional field left empty is valid; pairrequiredwith the other rules when a value must be present and well-formed.
Rules
| Builder | Passes when the value... |
|---|---|
validate.required() | is present and non-empty |
validate.integer() | parses as an integer |
validate.number() | parses as a number |
validate.boolean() | is exactly "true" or "false" |
validate.min(n) | is numeric and >= n (a float) |
validate.max(n) | is numeric and <= n |
validate.minLen(n) | is at least n characters (an int) |
validate.maxLen(n) | is at most n characters |
validate.pattern(re) | matches the RE2 source re (anchor with ^/$); a bad re throws when the rule is built |
validate.email() | looks like an email address: one @, a dot in the domain, no whitespace (Unicode's too), control character or Unicode format character (\p{Cf}: bidi controls such as U+202E / U+200E, zero-width characters, U+FEFF) |
validate.url() | is an absolute URL: a well-formed scheme and host (an IP literal closed by ] and followed only by the port or the path), a port of digits up to 65535, every % starting a two-hex-digit escape, no whitespace (Unicode's too), control character or Unicode format character (\p{Cf}) |
validate.datetime(format) | is a real date/time in the strftime format |
validate.oneOf(allowed) | is one of allowed (a whitelist) |
validate.noneOf(blocked) | is not one of blocked (a blacklist) |
validate.password(policy) | meets a password.Schema policy (length + classes) |
validate.custom(fn, msg) | the predicate fn(value) returns true (else msg) |
validate.withMessage(r, m) | (modifier) replaces rule r's message with m |
isInt, isFloat and isBool were removed in 0.28.0; use integer, number and boolean.
url accepts any scheme, javascript:// included. For a link you will put in a page, also require the scheme: validate.pattern("(?i)^https?://").
noneOf matches exactly and case-sensitively, like oneOf; for a case-insensitive blacklist use a pattern with the (?i) flag (validate.pattern("(?i)^(admin|root)$")) or normalise the value first.
custom takes a first-class func value - a top-level func(v as string) returning a bool:
import "validate.j" as validate;
func isHandle(v as string) {
return validate.ok({"h": $v}, {"h": [validate.pattern("^[a-z0-9_]+$")]});
}
def rules as map of string to list of validate.Rule init {
"username": [validate.required(), validate.custom(isHandle, "must be a valid handle")]
};A predicate may reject a value by throwing an error of its own kind (or a module's or library's kind, such as "uri" from uri.parse or "convert" from convert.toInt on a non-numeric value): the field then fails with msg rather than the exception escaping check. Other throws are passed on, because they are not about the value:
- kind
"runtime", a programmer error: a predicate with other parameters than onestring, an index out of range; - the generic kinds
"limit","timeout","closed","cancelled"and"net"(a predicate that looks something up hit a cap or the network); - a predicate returning anything but a
boolthrows kind"value".
validate.datetime(format) uses the time library's strftime codes, and checks both the format and calendar validity (month 13 / day 32 fail):
format | Accepts |
|---|---|
"%d.%m.%Y" | 25.12.2026 |
"%m/%d/%Y" | 12/25/2026 |
"%Y-%m-%d" | 2026-12-25 (ISO) |
"%Y-%m-%d %H:%M" | 2026-12-25 14:30 |
The default message is generic ("must be a valid date"); pair it with withMessage for a user-facing hint: validate.withMessage(validate.datetime("%d.%m.%Y"), "use DD.MM.YYYY").
validate.password(policy) delegates to the password module's validate: build a password.Schema with password.schema() and its with* builders (length range, per-class minimums), and the rule enforces it. The failure message is the policy's own failed-rule reasons joined with "; " (e.g. too short (minimum 8); needs at least 1 uppercase); collapse them to one hint with withMessage:
import "password.j" as password;
import "validate.j" as validate;
# at least 8 chars, at least one lower / upper / digit (symbols optional)
def policy as password.Schema init
password.withMinimums(password.withLength(password.schema(), 8, 64), 1, 1, 1, 0);
def rules as map of string to list of validate.Rule init {
"password": [validate.required(), validate.password($policy)]
};Because Jennifer has no closures, the policy travels in the Rule itself (a schema field), so validate imports password - it stays pure and runs on both binaries (the rule only reads a policy, it never generates).
Reading failures
| Call | Returns | Use |
|---|---|---|
validate.check(data, r) | list of Failure | every failure (empty = valid) |
validate.ok(data, r) | bool | a quick valid / invalid gate |
validate.messages(errs) | list of string | "field: message" lines for a log/flash |
validate.byField(errs) | map of string to list of string | field -> its messages, to re-render a form |
validate.localize(errs, t) | list of Failure | re-message with your own templates (i18n) |
One value, and throwing
For a single value, as in a factory that builds a domain type, skip the map:
| Call | Returns | Does |
|---|---|---|
validate.checkValue(field, value, rules) | list of Failure | check one value; rules is a list of Rule |
validate.ensure(data, rules) | check, throwing when anything fails | |
validate.ensureValue(field, value, rules) | checkValue, throwing when anything fails |
The throw is Error{kind: "validation"} (validate.ERROR_KIND), every failure in its message as field: message, joined with "; ": validation: percent: must be at most 100.0; percent: must be even. A blank value passes every rule but required here too, so name required when a value must exist.
# email.j, a module
import "validate.j" as validate;
export def struct Email { value as string };
export func fromString(s as string) {
validate.ensureValue("email", $s, [validate.required(), validate.email()]);
return Email{value: $s};
}Nothing stops other code from writing Email{value: "nope"} directly; the factory is a convention, not a guarantee.
A Failure is {field, rule, param, message}. rule is the failed rule's kind (e.g. "required", "min") - a stable id for machine-readable responses or your own message table - and param is the rule's argument in string form (a threshold, a joined choices list), the piece a localized message interpolates.
Non-English (or custom) messages
The built-in message is English. Because Failure carries a stable rule id and its param, you can re-render every message however you like with validate.localize(errs, templates): templates maps a rule id to a template where %param% and %field% are substituted. A rule not in the map keeps its default message, so a partial map only overrides what it names, and the result is a list of Failure (feed it to messages / byField):
import "validate.j" as validate;
def errs as list of validate.Failure init
validate.check({"email": "nope"}, {"email": [validate.required(), validate.email()]});
def de as map of string to string init {
"required": "ist erforderlich",
"email": "muss eine gültige E-Mail-Adresse sein",
"min": "muss mindestens %param% sein",
"minLen": "muss mindestens %param% Zeichen lang sein",
"oneOf": "muss eines von %param% sein"
};
def msgs as list of string init validate.messages(validate.localize($errs, $de));The markers are %name%-style (brace-free) so they never collide with the language's {expr} string interpolation; a template reads the same in a cooked or raw string. Substitution is a single left-to-right pass (a substituted value is never re-scanned), and a literal % is written %% - valid in cooked or raw alike, since string escapes never touch %.
For full internationalization, build the templates map from intl - one intl.tr("validate.min") per rule id, so the active locale picks the language - then hand it to localize. The rule ids (required, integer, number, boolean, min, max, minLen, maxLen, pattern, email, url, datetime, oneOf, noneOf, password, custom) are the catalog keys. (A password rule's default message is the password module's own English reasons; a "password" template replaces the whole message.)
Pairs with
web- validateweb.bodyForm($ctx)and respond422withvalidate.byFieldwhen invalid.rest- guard a request body before sending or after receiving.dotenv- validate a loaded config map.
Scope
Values are strings, so validation is over the string form (what forms / queries / config give you). A nested json.Value is not validated directly - pull the fields you need into a map of string to string first. There is no cross-field rule (e.g. "password == confirm"): a custom predicate sees only its own field's value, so compare the fields yourself after validate.check.
See also
- regex.md / uri.md / time.md / password.md - the
pattern/email/url/datetime/passwordbackends. - intl.md - the translation catalog to feed
localizefor non-English messages. - modules/index.md - the module catalog and import rules.
Academy talks
| Talk | What it shows |
|---|---|
| A production web API in Jennifer | field rules for API input |
API reference
Every exported function, struct and constant of validate, with its signature, generated from the module's doc comments: the validate API reference.