Integer Validation Regex (Positive or Negative)
• CronOS Team
regexintegervalidationtutorialnumber
Need to generate a regex pattern?
Use CronOS to generate any regex pattern you wish with natural language. Simply describe what you need, and we'll create the perfect regex pattern for you. It's completely free!
Integer Validation Regex (Positive or Negative)
Validate integers that can be positive, negative, or zero using a simple regex pattern with optional minus sign.
Pattern Breakdown
regex
^-?\d+$
Components
| Component | Description | Matches |
|---|---|---|
^ | Start anchor | Ensures match from string start |
-? | Optional minus | Optional minus sign |
\d+ | One or more digits | Integer digits |
$ | End anchor | Ensures match to string end |
Character Classes
-?- Optional minus sign (zero or one occurrence)\d- Any digit (0-9)+- Quantifier: one or more occurrences
Examples
Valid:
0123-123999999-1000000
Invalid:
12.5(decimal)+5(plus sign)123(leading space)123(trailing space)-(just minus sign)abc(non-numeric)
Implementation
JavaScript
javascript
const integerRegex = /^-?\d+$/;
integerRegex.test('123'); // true
integerRegex.test('-123'); // true
integerRegex.test('0'); // true
integerRegex.test('12.5'); // false (decimal)
integerRegex.test('+5'); // false (plus sign)
Python
python
import re
integer_regex = r'^-?\d+$'
bool(re.match(integer_regex, '123')) # True
bool(re.match(integer_regex, '-123')) # True
bool(re.match(integer_regex, '0')) # True
bool(re.match(integer_regex, '12.5')) # False (decimal)
Go
go
integerRegex := regexp.MustCompile(`^-?\d+$`)
integerRegex.MatchString("123") // true
integerRegex.MatchString("-123") // true
integerRegex.MatchString("0") // true
integerRegex.MatchString("12.5") // false (decimal)
Limitations
- Includes zero: Matches
0(and-0) - No leading zeros: Accepts
0123(may want to prevent this) - No size limit: Doesn't enforce maximum/minimum value
- String validation: Validates string format, not actual integer type
- No scientific notation: Doesn't support
1e5format
When to Use
- Integer input validation (any sign)
- General number input forms
- When you need flexible integer validation
- Form input validation
- Quick integer format checking
For production, consider:
- Preventing leading zeros:
^-?(0|[1-9]\d*)$ - Adding value range validation
- Converting to integer type after validation
- Handling edge cases for very large numbers
- Supporting plus sign if needed:
^[+-]?\d+$
Need to generate a regex pattern?
Use CronOS to generate any regex pattern you wish with natural language. Simply describe what you need, and we'll create the perfect regex pattern for you. It's completely free!