Skip to main content

length

$length

Validates that the length of a string or array falls within specified bounds (inclusive). Can specify minimum, maximum, exact length, or any combination of min/max.

For strings, length is measured in characters. For arrays, length is measured in elements.

Parameters

  • exact (number, optional): Exact required length. If specified, min/max are ignored.

  • min (number, optional): Minimum length (inclusive). If omitted, no lower bound.

  • max (number, optional): Maximum length (inclusive). If omitted, no upper bound.

  • With {min: 3, max: 10}: strings "abc" to "abcdefghij", arrays with 3-10 elements

  • With {exact: 5}: string "hello", array [1,2,3,4,5]

  • With {min: 3, max: 10}: string "ab" (too short), array with 11 elements (too long)

  • With {exact: 5}: string "hi" (wrong length), array [1,2,3] (wrong length)

Example

// Validate a username is between 3 and 32 characters
new Schema('string').validator({$length: {min: 3, max: 32}})

// Require an exact number of elements in an array
new Schema('array').validator({$length: 3})

// Validate a fixed-length code (e.g., ISO country code)
new Schema('string').normalizer('$uppercase').validator({$length: {exact: 2}})