Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isDigits

Checks if a string contains only digit characters (0-9).

TypeScript
Copied!
1/**
2 * Checks if a string contains only digit characters (0-9).
3 *
4 * @param str - The input string to validate.
5 * @returns True if the string contains only digits, false otherwise.
6 */
7export function isDigits(str: string): boolean {
8  return /^\d+$/.test(str);
9}
  • Strict Digit Enforcement

    Ensures the string contains only numeric characters (0–9), rejecting any letters, symbols, or whitespace.

  • Efficient Regex-Based Check

    Utilizes a simple and performant regular expression for quick validation.

  • Lightweight and Dependency-Free

    Does not rely on external libraries, making it suitable for use in any environment.

Tests | Examples

TypeScript
Copied!
1test('isDigits - returns true for digits only', () => {
2  expect(isDigits('123456')).toBe(true);
3});
4
5test('isDigits - returns false for string with letters', () => {
6  expect(isDigits('123a456')).toBe(false);
7});
8
9test('isDigits - returns false for empty string', () => {
10  expect(isDigits('')).toBe(false);
11});
12
13test('isDigits - returns false for spaces and digits', () => {
14  expect(isDigits(' 123 ')).toBe(false);
15});
16
17test('isDigits - returns false for symbols with digits', () => {
18  expect(isDigits('123-456')).toBe(false);
19});

Common Use Cases

  • Validating Numeric Form Fields

    Confirm user input in fields like ZIP codes, security codes, or numeric IDs.

  • Preprocessing Before Parsing

    Verify that a string can safely be converted to a number without throwing errors.

  • Filtering Data Rows

    Ensure dataset values (e.g. CSV columns) consist strictly of digits before further processing.

  • Sanitization Checks in APIs

    Validate parameters expected to contain only numeric identifiers.

Codebase: Utilities -> Validation -> isDigits | Yevhen Klymentiev