Validation
Positive Integer Regex
Quantities, page numbers and counts must be whole numbers above zero. This pattern requires the first digit to be between one and nine, which rules out zero itself and any leading zeros, and then allows any number of further digits. The anchors make sure the input contains nothing else, so signs, decimal points, spaces and thousands separators are all rejected. Remember that a regex checks only the text shape, not the size of the value; a very long digit string still passes, so also compare the parsed number against a maximum if your field has an upper limit.
Pattern (JavaScript)
/^[1-9]\d*$/Starts at the start of the line/string, then one of the characters 1-9, then a digit (0-9), zero or more times, then the end of the line/string.
Examples
Matches
- ✓ 1
- ✓ 42
- ✓ 1000000
Does not match
- ✗ 0
- ✗ -5
- ✗ 012
Try it
0 matches (JavaScript engine)
1
42
1000000
0
-5
012Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^[1-9]\d*$/g;
const text = "1";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^[1-9]\d*$')
text = '1'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^[1-9]\d*$/';
$text = '1';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^[1-9]\\d*$");
String text = "1";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[1-9]\d*$`)
text := "1"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^[1-9]\d*$");
var text = "1";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^[1-9]\d*$").unwrap();
let text = "1";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^[1-9]\d*$/
text = '1'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- How do I allow zero as well?
- Use ^(0|[1-9]\d*)$. The first branch accepts a single zero and the second keeps rejecting leading zeros.
- Why are leading zeros rejected?
- Values like 007 can be read as octal by some parsers or simply look wrong in a form. Rejecting them keeps every number in one normal form.
- Does this limit how big the number can be?
- No. It checks digits only. Parse the value and compare it with your maximum, and watch for numbers above Number.MAX_SAFE_INTEGER in JavaScript.