Text Length Validation Regular Expression

Text length validation is a common requirement in forms and data validation. Regular expressions provide a concise way to enforce minimum length, maximum length, or a specific length range for text input. This is particularly useful for passwords, usernames, comments, and other user-generated content. For validating the number of lines in text, see the number of lines validation article.

Length Range Validation (8-32 characters)

This pattern validates that text is between 8 and 32 characters in length, inclusive. This is commonly used for passwords, usernames, and other fields where both minimum and maximum lengths are required.

^.{8,32}$

Explanation

  • ^ - Start of the string.
  • . - Matches any character (except newline by default).
  • {8,32} - Quantifier that specifies the preceding pattern must occur between 8 and 32 times (inclusive).
  • $ - End of the string.

Implementation

const lengthRangeRegex = /^.{8,32}$/;
const isValidLength = (text) => lengthRangeRegex.test(text);

Test Cases

TextValid
12345678
abcdefgh
Test1234
A1B2C3D4E5F6G7H8
12345678901234567890123456789012
1234567
abc
(empty string)
123456789012345678901234567890123
This is a very long text that exceeds the maximum allowed length

Minimum Length Validation (8+ characters)

This pattern validates that text has a minimum of 8 characters with no upper limit. This is useful for password fields where you want to enforce a minimum security requirement without limiting maximum length.

^.{8,}$

Explanation

  • ^ - Start of the string.
  • . - Matches any character (except newline by default).
  • {8,} - Quantifier that specifies the preceding pattern must occur at least 8 times with no upper limit.
  • $ - End of the string.

Implementation

const minLengthRegex = /^.{8,}$/;
const isValidMinLength = (text) => minLengthRegex.test(text);

Test Cases

TextValid
12345678
abcdefgh
Test1234
A very long text that is definitely more than 8 characters
12345678901234567890123456789012345678901234567890
1234567
abc
(empty string)
short

Maximum Length Validation (0-32 characters)

This pattern validates that text does not exceed 32 characters. It allows any length from 0 (empty string) up to 32 characters. This is useful for fields like titles, short descriptions, or comments where you want to limit verbosity.

^.{0,32}$

Explanation

  • ^ - Start of the string.
  • . - Matches any character (except newline by default).
  • {0,32} - Quantifier that specifies the preceding pattern can occur from 0 to 32 times (inclusive).
  • $ - End of the string.

Implementation

const maxLengthRegex = /^.{0,32}$/;
const isValidMaxLength = (text) => maxLengthRegex.test(text);

Test Cases

TextValid
(empty string)
a
12345678
Test1234
12345678901234567890123456789012
123456789012345678901234567890123
This is a very long text that exceeds the maximum allowed length
A very long text with more than thirty-two characters in total