Skip to content

validateStringLength

Validates that a value is a string whose length falls within a specified inclusive range. This helper does not modify or coerce the input. It only checks the raw string length.

It never throws and never mutates input. Use it when you need to enforce minimum and maximum length constraints before applying deeper validation or normalization.

Signature

function validateStringLength(
    value: unknown,
    min: number,
    max: number
): string | undefined

Parameters

Name Data type Description
value unknown The value to validate as a string.
min number Minimum allowed value (inclusive).
max number Maximum allowed value (inclusive).

Returns

One of:

  • The original string if its length is within the range.
  • undefined if the value is not a string or its length is out of range.

Behavior

  • Only accepts values of type string.
  • Rejects strings shorter than min.
  • Rejects strings longer than max.
  • Never throws and never mutates input.
  • Never coerces values (for example, numbers are not converted to strings).

Examples

validateStringLength("abc", 1, 5)
// "abc"

validateStringLength("hello", 1, 5)
// "hello"

validateStringLength("", 1, 5)
// undefined

validateStringLength("toolong", 1, 3)
// undefined

validateStringLength(123, 1, 5)
// undefined

Notes

  • This validator does not trim whitespace. " abc " is validated as length 5.
  • Suitable for validating identifiers, names, tokens, and any field with explicit length constraints.
  • The helper is pure, side-effect-free, and never throws.