Regex for numbers only (digits 0-9)

This pattern accepts a line only if every character is a digit. It is the usual check for PIN-style fields, quantities and ID numbers where no spaces, signs or decimal points are allowed.

The pattern

/^\d+$/gm

The tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.

How it works

^
Start of the line (with the m flag) or of the whole value.
\d+
One or more digits, 0 to 9.
$
End of the line or value, so no other character can follow.

Examples

Matches

  • 0
  • 12345
  • 007

Does not match

  • 12a3
  • 12 34
  • -5
  • 3.14

Use it in JavaScript

const re = /^\d+$/gm;

// Find every match in a block of text
const found = text.match(re);

// Validate that a whole value matches (no stray characters around it)
const exact = new RegExp('^(?:' + re.source + ')$', re.flags.replace('g', ''));
const isValid = exact.test(value);

Limits and tips

  • An empty string does not match because + needs at least one digit. Use ^\d*$ if an empty value is allowed.
  • For a fixed length, use a count: ^\d{6}$ for exactly six digits or ^\d{4,8}$ for four to eight.
  • For decimals and negative numbers use ^-?\d+(\.\d+)?$.
  • In JavaScript \d matches only 0-9, so Arabic-Indic or other Unicode digits are rejected.

Frequently asked questions

How do I allow only numbers in an input field?

Test the value against ^\d+$ on input or on submit. Also set inputmode="numeric" so mobile keyboards show digits.

Does it allow decimals or negative numbers?

No. Use ^-?\d+(\.\d+)?$ to allow an optional minus sign and decimal part.