Skip to content
Jennifer Programming Language

validate API reference

Declarative validation of a map of string to string (a form body, a query, a config) against a rule set, returning a structured error list instead of ad-hoc per-field if checks. Rules compose as value-semantic descriptors built by the validate.required / integer / min / pattern / email / ... family; group them per field in a map of string to list of Rule and call validate.check. Pure Jennifer over regex + uri + time + password + convert + lists + strings + maps, so it runs on both binaries.

Values are strings (the shape web.bodyForm / dotenv / a query string produce): a type rule (integer / number / boolean) checks the string parses; min / max parse then compare; minLen / maxLen measure the string. A field that is absent or blank passes every rule except required - so an optional field left empty is valid. Only the fields named in the rule set are checked; extra data keys are ignored.

checkValue checks a single value against a list of Rule, and ensure / ensureValue throw Error{kind: "validation"} instead of returning failures, for a factory that must not build an invalid value.

Import with import "validate.j" as validate;. See the validate guide for prose and examples.

Contents

NameWhat it is
booleanRequire the value to be exactly "true" or "false".
byFieldGroup error messages by field (for re-rendering a form with per-field errors).
checkValidate data against a rule set, returning every failure.
checkValueValidate one value against its rules, returning every failure.
customA custom rule: fn is a func(value as string) returning true when valid.
datetimeRequire the value to be a valid date/time in the given strftime format (time's format codes):...
emailRequire the value to look like an email address: one "@", a dot in the domain, no whitespace (Unicode's too...
ensureLike check, but throw when anything fails: for a constructor or factory that must not build an invalid va...
ensureValueLike checkValue, but throw when anything fails.
integerRequire the value to parse as an integer.
localizeRe-render failures with caller-supplied per-rule message templates - for non-English messages, or a house s...
maxRequire the numeric value to be at most n.
maxLenRequire the string to be at most n characters (runes).
messagesRender an error list as "field: message" strings (for logging or a flash).
minRequire the numeric value to be at least n.
minLenRequire the string to be at least n characters (runes).
noneOfReject the value if it is one of blocked (a blacklist - reserved usernames, banned words).
numberRequire the value to parse as a number (int or float).
okWhether data satisfies every rule (a short-circuit over check).
oneOfRequire the value to be one of allowed.
passwordRequire the value to satisfy a password policy - length bounds and per-class minimums - by delegating to ...
patternRequire the value to match an RE2 regular expression (anchored yourself with ^ / $ if you want a full m...
requiredRequire the field to be present and non-empty.
urlRequire the value to be an absolute URL: a well-formed scheme and host, a port up to 65535, no whitespace (...
withMessageOverride the message of an already-built rule (fluent).
Failurestruct: One validation failure.
Rulestruct: One validation rule (descriptor).
constantsthe module's constants

Functions

boolean

jennifer
validate.boolean()

Require the value to be exactly "true" or "false".

Returns Rule
the rule

byField

jennifer
validate.byField(errs as list of Failure)

Group error messages by field (for re-rendering a form with per-field errors).

errs
the failures
Returns map of string to list of string
field -> its messages

check

jennifer
validate.check(
    data as map of string to string,
    rules as map of string to list of Rule)

Validate data against a rule set, returning every failure. Empty means valid.

data
the field values
rules
rules per field
Returns list of Failure
the failures (empty when valid)

checkValue

jennifer
validate.checkValue(field as string, value as string, rules as list of Rule)

Validate one value against its rules, returning every failure. The value counts as present, so a blank one still passes every rule but required.

field
the name the failures carry
value
the value
rules
its rules, in order
Returns list of Failure
the failures (empty when valid)

custom

jennifer
validate.custom(fn as func, message as string)

A custom rule: fn is a func(value as string) returning true when valid. A predicate that throws an error of its own kind (or a module's or a library's, such as convert.toInt's "convert") marks the value invalid. Kind "runtime" (a programmer error: wrong parameters, an index out of range) and the generic kinds ("limit", "timeout", "closed", "cancelled", "net") are passed on by check, and a result that is not a bool throws kind "value".

fn
the predicate
message
the message when the predicate fails
Returns Rule
the rule

datetime

jennifer
validate.datetime(format as string)

Require the value to be a valid date/time in the given strftime format (time's format codes): "%d.%m.%Y" for dd.mm.yyyy, "%m/%d/%Y" for mm/dd/yyyy, "%Y-%m-%d" for ISO, "%Y-%m-%d %H:%M" for a date-time. The value must both match the format and be a real calendar date (month 13 or day 32 fail), since it is checked with time.parse. Pair with withMessage for a user-facing "use DD.MM.YYYY" hint.

format
the strftime format the value must match
Returns Rule
the rule

email

jennifer
validate.email()

Require the value to look 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). A shape check, not RFC 5322.

Returns Rule
the rule

ensure

jennifer
validate.ensure(
    data as map of string to string,
    rules as map of string to list of Rule)

Like check, but throw when anything fails: for a constructor or factory that must not build an invalid value.

data
the field values
rules
rules per field
Throws Error
kind "validation", every failure in the message as field: message, joined with "; "

ensureValue

jennifer
validate.ensureValue(
    field as string,
    value as string,
    rules as list of Rule)

Like checkValue, but throw when anything fails.

field
the name the message carries
value
the value
rules
its rules, in order
Throws Error
kind "validation", every failure in the message

integer

jennifer
validate.integer()

Require the value to parse as an integer.

Returns Rule
the rule

localize

jennifer
validate.localize(
    failures as list of Failure,
    templates as map of string to string)

Re-render failures with caller-supplied per-rule message templates - for non-English messages, or a house style. templates maps a rule id (the Failure.rule, e.g. "min" / "email") to a template string; %param% is replaced with the failure's param (a threshold, joined choices) and %field% with its field name. A rule not in templates keeps its default message, so a partial map overrides only the rules it names. The templates can come from anywhere - a literal map, a config, or intl.tr per rule id. Returns the failures with message replaced, so it composes with messages / byField. The markers are %name%-style (brace-free) on purpose: they never collide with the language's {expr} string interpolation, so a template reads the same in a cooked or raw string. Substitution is a single pass (a substituted value is never re-scanned), and a literal % is written %%.

failures
the failures from check
templates
rule id -> message template
Returns list of Failure
the failures with localized messages

max

jennifer
validate.max(n as float)

Require the numeric value to be at most n.

n
the maximum
Returns Rule
the rule

maxLen

jennifer
validate.maxLen(n as int)

Require the string to be at most n characters (runes).

n
the maximum length
Returns Rule
the rule

messages

jennifer
validate.messages(errs as list of Failure)

Render an error list as "field: message" strings (for logging or a flash).

errs
the failures
Returns list of string
one line per error

min

jennifer
validate.min(n as float)

Require the numeric value to be at least n.

n
the minimum
Returns Rule
the rule

minLen

jennifer
validate.minLen(n as int)

Require the string to be at least n characters (runes).

n
the minimum length
Returns Rule
the rule

noneOf

jennifer
validate.noneOf(blocked as list of string)

Reject the value if it is one of blocked (a blacklist - reserved usernames, banned words). Exact, case-sensitive matching, like oneOf; for a case-insensitive blacklist use a pattern with the (?i) flag, or normalise the value first.

blocked
the forbidden values
Returns Rule
the rule

number

jennifer
validate.number()

Require the value to parse as a number (int or float).

Returns Rule
the rule

ok

jennifer
validate.ok(
    data as map of string to string,
    rules as map of string to list of Rule)

Whether data satisfies every rule (a short-circuit over check).

data
the field values
rules
rules per field
Returns bool
true when valid

oneOf

jennifer
validate.oneOf(allowed as list of string)

Require the value to be one of allowed.

allowed
the permitted values
Returns Rule
the rule

password

jennifer
validate.password(policy as pw.Schema)

Require the value to satisfy a password policy - length bounds and per-class minimums - by delegating to the password module's validate. Build policy with password.schema() and its with* builders. On failure the message is the policy's own failed-rule reasons, joined; override with withMessage for a single user-facing hint. Like every rule but required, an absent or blank value is skipped - pair with required to also demand a value.

policy
the policy to enforce (a Schema from the password module)
Returns Rule
the rule

pattern

jennifer
validate.pattern(re as string)

Require the value to match an RE2 regular expression (anchored yourself with ^ / $ if you want a full match). The source is compiled here, so a bad one fails when the rule is built, not when a value is checked.

re
the regex source
Returns Rule
the rule
Throws Error
when re is not a valid RE2 expression

required

jennifer
validate.required()

Require the field to be present and non-empty. Every other rule is skipped for an absent or blank field, so pair required with them to also validate a value.

Returns Rule
the rule

url

jennifer
validate.url()

Require the value to be an absolute URL: a well-formed scheme and host, a port up to 65535, no whitespace (Unicode's too), control character or Unicode format character (\p{Cf}: bidi controls, zero-width characters, U+FEFF). Any scheme passes, javascript:// too; add pattern("(?i)^https?://") for a link you render.

Returns Rule
the rule

withMessage

jennifer
validate.withMessage(r as Rule, message as string)

Override the message of an already-built rule (fluent).

r
the rule
message
the message to use on failure
Returns Rule
the updated rule

Structs

Failure

One validation failure. rule is a stable id (the rule kind) and param is the rule's argument in string form (a threshold, a joined choices list) - the two a caller needs to render a custom or localized message via localize. The built-in message is the default (English).

jennifer
def struct Failure {
    field as string,
    rule as string,
    param as string,
    message as string
};
field
the field that failed
rule
the rule kind that failed (the stable message id)
param
the rule's argument for message interpolation ("" if none)
message
the default (English) human-readable message

Rule

One validation rule (descriptor). Built by the rule family (required / integer / min / ...); not usually constructed directly.

jennifer
def struct Rule {
    kind as string,
    num as float,
    intVal as int,
    str as string,
    choices as list of string,
    fn as func,
    schema as pw.Schema,
    message as string
};
kind
the rule kind ("required", "integer", "min", "pattern", ...)
num
the numeric threshold for min / max
intVal
the length threshold for minLen / maxLen
str
the regex source for pattern
choices
the allowed values for oneOf / the blocked values for noneOf
fn
the predicate for custom (a func(value as string) -> bool)
schema
the policy for password (a Schema from the password module)
message
an override message ("" = use the rule's default)

Constants

validate.ERROR_KIND as string
The kind of the error ensure and ensureValue throw.