Request Validation

Checks req.body, req.query and req.params against a schema before your handler runs. Values are converted to the types you declare, defaults are filled in, and a request that doesn't fit is answered with a 400 listing every problem — so the handler can assume its input is the right shape.

bxsapp.post( "/users",
	boxExpressJSON(),
	boxExpressValidate( {
		body: {
			email: { type: "email", required: true },
			name: { type: "string", required: true, trim: true, maxLength: 80 },
			age: { type: "integer", min: 18 },
			role: { type: "string", oneOf: [ "admin", "member" ], default: "member" }
		},
		query: {
			notify: { type: "boolean", default: false }
		}
	} ),
	( req, res ) => {
		var user = users.create( req.valid.body )     // email, name, age, role — nothing else
		res.status( 201 ).json( user )
	}
)

Put it after the body parser: it reads req.body, it doesn't parse it.

What the handler gets

req.valid holds body, query and params — whichever the schema covers — containing only the fields the schema names, converted. That makes it safe to hand to a model: a client that adds "isAdmin": true to its JSON doesn't get it into req.valid.body.

req.body and req.query are also updated in place (converted values, defaults), and keep any other fields unless you say otherwise (unknown, below). req.params isn't — read converted route params from req.valid.params.

What a failure looks like

HTTP/1.1 400 Bad Request

{"error":true,"message":"Validation failed","errors":[
  {"in":"body","field":"email","message":"must be a valid email address"},
  {"in":"body","field":"age","message":"must be at least 18"},
  {"in":"query","field":"notify","message":"must be true or false"}
]}

Every problem is reported, not just the first. Nested fields are named by path: address.city, tags[2]. The handler doesn't run.

Rules

RuleApplies toMeaning
typeanyOne of the types below; "any" if omitted
requiredanyThe field must be present and not empty
defaultanyUsed when the field is missing or empty
min, maxinteger, numberSmallest and largest value
minLength, maxLengthstringsLength in characters
patternstringsA regular expression the value must match
oneOfsimple valuesAn array of allowed values, compared exactly
trimstringsStrip surrounding whitespace before checking
itemsarrayRules for each element
minItems, maxItemsarrayNumber of elements
fieldsstructRules for a nested object's fields
validateanyYour own check — see below
messageanyReplaces the default message for this field
TypeAcceptsreq.valid holds
stringAny simple valueA string
integerA whole number, or a string of digits ("42", "-7")A number
numberA number, or a numeric string ("0.25")A number
booleantrue/false, or "true", "false", "1", "0", "yes", "no", "on", "off"A boolean
emailSomething shaped like [email protected]The string
urlAn http or https URL with a hostThe string
uuidA UUID, in the standard form or the one createUUID() producesThe string
dateISO 8601: 2026-11-15 or 2026-11-15T09:30:00ZThe string
arrayAn arrayThe array, items converted
structAn objectIts declared fields, converted
anyAnythingThe value unchanged

Conversion is what makes this useful for query strings and form posts, where everything arrives as text: ?page=2 becomes the number 2. It's deliberately strict — "1e3", " 7" and "1.0" are not integers.

Missing vs. empty. A field that's absent, JSON null, or an empty string counts as missing: it gets its default, or fails required. The one exception is an optional string field, where "" is a valid value. Whitespace only counts as empty if trim is on.

Your own check. validate receives the converted value and the request. Return true to accept; return false, or a string to use as the message, to reject:

bxsendDate: { type: "date", required: true, validate: ( value, req ) => {
	return value >= req.body.startDate ? true : "must not be before startDate"
} }

It runs after the built-in rules pass, so value is already the right type. Fields are checked independently and in no particular order, so a cross-field check like this one should read the other field from req.body, not req.valid.

Options

boxExpressValidate( schema, options ):

  • unknown — what to do with fields the schema doesn't name, at any depth: "allow" (default) leaves them on req.body/req.query; "strip" removes them; "reject" makes each one an error ("is not allowed").

  • status — the failure status, 400 by default. 422 is a common alternative.

  • onError — ( errors, req, res, next ) => {...}, called instead of sending the default response; for re-rendering a form with messages, or your own error format:

    bxsboxExpressValidate( schema, { onError: ( errors, req, res, next ) => {
    	res.status( 400 ).render( "signup", { errors: errors, values: req.body } )
    } } )
    

Things worth knowing

  • A mistake in the schema throws when the route is registered — an unknown type or rule name (requried: true), an invalid pattern. It can't silently validate nothing.
  • email and url check shape, not existence. [email protected] passes. To know an address is real, send it a message.
  • pattern is a regular expression run on client input; avoid nested quantifiers like (a+)+, and set a maxLength alongside it.
  • Validate route params here, or constrain them in the path — see Path patterns. A path constraint decides which route matches (and falls through to a 404); validation answers a 400 saying what was wrong.
  • trim doesn't reach array items (0.2.27): items: { type: "string", trim: true } leaves " a " as it is. Fields of a struct are trimmed. Trim array elements in the handler.
  • date values stay strings. Parse them (parseDateTime()) where you use them.
  • Not included: validating headers or cookies, conditional rules ("required if another field is set" — use validate), and generating API documentation from a schema.