Numbers Regex Javascript Validator

Search...

⌘K

Numbers Regex Javascript Validator

Search...

⌘K


Numbers Regex Javascript Validator

Numbers Regex Javascript Validator

Use the Numbers Regex JavaScript Validator to check patterns for integers, decimals, and signed or formatted numbers. Whether you’re building forms or financial tools, regex is a powerful way to ensure data accuracy. You can also explore our JavaScript Regex Tester to debug patterns live, or combine it with tools like the Token Generator for numeric authentication, and the Base64 Decoder for decoding values before validation.

28193
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Match information
Match 1: "28193" at index 0
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

What is Numbers Regex?


In JavaScript, regex (regular expressions) are often used to validate and match numeric inputs such as whole numbers, decimals, and formatted values like currency. This is especially useful in forms, financial calculations, and input validation where the structure of numeric data matters.


JavaScript regex provides concise patterns to distinguish valid numbers and reject anything unexpected, like letters or malformed punctuation.


Regex Patterns for Number Validation


  1. Integer Validation


    Validates whole numbers with no symbols or decimal points.


    const regex = /^\d+$/;


    Matches: "123", "2024"

    Doesn’t match: "12.3", "-100"


  2. Decimal Number Validation


    Validates numbers with optional decimals.


    const regex = /^\d+\.\d+$/;


    Matches: "3.14", "99.999"

    Doesn’t match: "100", "abc"


  3. Signed Number Validation


    Allows optional negative or positive sign.


    const regex = /^[+-]?\d+(\.\d+)?$/;


    Matches: "-45", "+99.99", "0"

    Doesn’t match: "--12", "100+"


  4. Formatted Numbers with Commas


    Matches numbers like 1,000 or 12,345,678.


    const regex = /^\d{1,3}(,\d{3})*$/;


    Matches: "1,000", "100,000"

    Doesn’t match: "1000", "1,,000"


How to Validate Numbers in JavaScript


Use the built-in RegExp class or regex literals with methods like .test() or .match():


const number = "12345";
const pattern = /^\d+$/;

console.log(pattern.test(number)); // true

The test() method executes a search for a match between your regular expression and a specified string. It returns true if the pattern matches the string; otherwise, it returns false. This makes it an efficient way to quickly check if user input meets a specific format—for example, a numeric-only validation.

The method returns a boolean value:

  • true if the pattern matches the string

  • false if it doesn't


This differs from the search() method, which instead returns the index of the match (or -1 if no match is found).

In summary:

  • Use test() to simply check if a match exists and get a true or false result.

  • If you need to know where in the string the match occurs, use search() instead.

This makes test() particularly handy for quick validation checks, like confirming if a string contains only digits.

Tip:
Be explicit about the value you're testing. The string you pass is what gets matched against the regex. If you omit it or accidentally pass undefined, JavaScript will coerce it to the string "undefined", which almost never produces the result you expect.


You can test your custom regex using our interactive JavaScript Regex Tester.


How Does test() Behave with Global Regex and Different Strings?


When you use the test() method with a regex that has the global (g) flag, there's a quirk you should keep in mind: the regex maintains a lastIndex property across repeated tests. This means that if you call test() multiple times—even on different strings—the search continues from where it last left off.

  • If test() finds a match, lastIndex increases to the position just after the match.

  • As long as you keep getting true, the regex doesn't reset for new strings. The index continues to climb, which can lead to missed matches if you're testing different values in succession.

  • But as soon as test() fails (returns false), lastIndex resets to 0.

Why does this matter?

If you're validating several numbers or fields in a form using the same global regex object, and you don't reset lastIndex manually, unexpected false negatives can crop up. This often surprises developers, especially when cross-testing multiple strings.

Example Scenario

const regex = /\d+/g;

regex.test("123");    // true (lastIndex now at 3)
regex.test("456");    // true (lastIndex now at 3)
regex.test("789");    // true (lastIndex now at 3)
regex.test("abc");    // false (lastIndex resets to 0)

Notice above: after any false, the index resets, but before that, if you test new strings, the regex may start from a position past the beginning—possibly missing a match at the start.

Best Practice:
If you're using the same global regex for different strings, call regex.lastIndex = 0 before each new test, or just avoid the global flag unless you actually need it for iterative matching within a single string (e.g., with .exec() in a loop).

This small detail will help you avoid head-scratching moments while wrangling your numeric validations.


When to Use test(), exec(), or match()


When validating numeric input or detecting if a string matches a given pattern, reach for .test() on your regex. This method is perfect for quick yes-or-no checks, as it simply tells you whether your pattern is present (true or false). For example, use it to verify if a user’s input is a valid number before proceeding with form submission.

const regex = /^\d+$/;
console.log(regex.test("12345")); // true

If you need more detail—such as extracting matched portions of the string or gathering capture groups—use .exec(). This method returns an array of results (or null if no match), and is especially handy when your regular expression contains groups or you want all matches in a string.

Likewise, the string method .match() works similarly to .exec(), but is called on the string itself. It’s great when you want to directly pull matching results for further processing.

In summary:

  • Use .test() for simple yes/no validation.

  • Use .exec() or .match() when you need match details or extracted values.

This way, you’ll always pick the right approach for your number validation needs, whether you’re building forms, calculators, or authentication workflows.


test() vs. String.prototype.search(): Key Differences


When checking if your string matches a pattern, you'll often reach for either test() or search(), but they're not interchangeable.

  • test() (from the RegExp object) returns a simple true or false—perfect for validation checks. For example, if you only care whether your input is a valid number format, use pattern.test(input) to get a boolean result.

  • search() (a method directly on strings) instead gives you the position of the match (the starting index), or -1 if there’s no match. This is handy if you need to know where in your string the pattern occurs.

In short:

  • Use .test() when you want a clear yes/no answer.

  • Use .search() if you need to locate the match inside your string.


How test() Behaves with Stateful Regex (global and sticky Flags)


When validating numeric inputs, it's important to understand that some regular expressions in JavaScript are "stateful." This happens when you add the g (global) or y (sticky) flags to your regex. These flags tell the regex engine to keep track of where it left off in the string, using a property called lastIndex.

Here's what this means in practice:

  • Whenever you use the .test() method on a regex with a g or y flag, the regex remembers its position within the string. If .test() finds a match, lastIndex moves forward to just after that match.

  • If you call .test() again with the same regex (and flag), it will start searching from the last position, not from the beginning.

  • If .test() can't find a new match, lastIndex automatically resets to 0.

  • This behavior persists—even across different strings—until .test() returns false.

Example Scenario:

const regex = /foo/g;

console.log(regex.test("foo"));        // true (searches from 0)
console.log(regex.lastIndex);          // 3 (after "foo")

console.log(regex.test("foo"));        // false (no "foo" after position 3)
console.log(regex.lastIndex);          // 0 (reset)

console.log(regex.test("barfoo"));     // true (finds "foo" at position 3)
console.log(regex.lastIndex);          // 6

This can catch you by surprise if you’re reusing regex objects across multiple calls or strings in your validation logic. For most number validation scenarios—where you're testing fresh strings each time—this might not matter. But in more complex patterns or loops, resetting the regex (or avoiding the g/y flags unless necessary) helps prevent unexpected results.


How test() Behaves with Stateful Regex (global and sticky Flags)


When validating numeric inputs, it's important to understand that some regular expressions in JavaScript are "stateful." This happens when you add the g (global) or y (sticky) flags to your regex. These flags tell the regex engine to keep track of where it left off in the string, using a property called lastIndex.

Here's what this means in practice:

  • Whenever you use the .test() method on a regex with a g or y flag, the regex remembers its position within the string. If .test() finds a match, lastIndex moves forward to just after that match.

  • If you call .test() again with the same regex (and flag), it will start searching from the last position, not from the beginning.

  • If .test() can't find a new match, lastIndex automatically resets to 0.

  • This behavior persists—even across different strings—until .test() returns false.

Example Scenario:

const regex = /foo/g;

console.log(regex.test("foo"));        // true (searches from 0)
console.log(regex.lastIndex);          // 3 (after "foo")

console.log(regex.test("foo"));        // false (no "foo" after position 3)
console.log(regex.lastIndex);          // 0 (reset)

console.log(regex.test("barfoo"));     // true (finds "foo" at position 3)
console.log(regex.lastIndex);          // 6

This can catch you by surprise if you’re reusing regex objects across multiple calls or strings in your validation logic. For most number validation scenarios—where you're testing fresh strings each time—this might not matter. But in more complex patterns or loops, resetting the regex (or avoiding the g/y flags unless necessary) helps prevent unexpected results.


How .test() with the Global Flag Impacts lastIndex


If you use a regex with the global (g) flag in JavaScript, calling .test() does a bit more than just check for a match—it actually updates the regex’s lastIndex property. Here’s what that means for your validation logic:

  • Every successful .test() increments lastIndex: Each time .test() finds a match, it moves lastIndex to just after the match, so future tests start searching from there instead of the beginning of the string.

  • On a failed match, lastIndex resets to 0: If .test() fails (returns false), it’ll reset lastIndex back to zero, ready to start again from the top next time.

  • Persistence across strings: Watch out! If you're using the same regex instance on multiple different strings, lastIndex keeps climbing whenever .test() returns true, even if the input strings are completely different. This can catch you off guard with unexpected results, especially in loops or validation libraries like Joi or validator.js.

Example

const regex = /foo/g;

regex.test("foo");        // true   (lastIndex becomes 3)
regex.test("foo");        // false  (lastIndex resets to 0)
regex.test("barfoo");     // true   (lastIndex becomes 6)
regex.test("foobarfoo");  // true   (lastIndex becomes 3)

So, when using the global flag, be mindful of lastIndex—reuse of regex objects can sometimes lead to bugs that are tricky to spot. For one-off validations, consider avoiding the global flag, or always reset lastIndex to 0 before reusing a regex instance.


What Happens to lastIndex When test() Returns false?


When using regex patterns with the global (g) or sticky (y) flags in JavaScript, the lastIndex property keeps track of where in the string the next match attempt will start. If you call .test() and it returns false, JavaScript automatically resets the regular expression’s lastIndex property to 0.

This means that the next matching operation will always begin at the start of the string—not from where the previous attempt ended. Keep this behavior in mind, especially when running validation across multiple values or reusing patterns in loops, since a false result resets your search position.


Where to Find the Official test() Method Specification


If you need the technical details for how the RegExp.prototype.test() method works under the hood, you can find its definition in the ECMAScript Language Specification. This is the official reference maintained by the standards committee, and it's the go-to resource for the formal behavior of JavaScript features—including regex methods like .test(). It's a bit dense, but it's the definitive guide on how pattern matching is supposed to operate in JavaScript engines.


Pro Tips


  • Use the Numbers Regex Go Validator or Numbers Regex Java Validator for server-side verification of numeric inputs.

  • Use the Base64 Decoder if your numeric data is encoded before validation.

  • Combine with the Token Generator if you’re building numeric-based authentication systems like OTPs.

  • Avoid accepting parseFloat() as validation—it’s not strict and may allow invalid strings like "123abc" to partially pass.

  • Always sanitize numeric input alongside regex validation to prevent injection risks or malformed formatting.


Using and for Number Validation


  • is a quick way to check if a string matches a pattern, returning a simple true or false. It's perfect for validation in forms or quick logic checks.

  • For more detailed match information, use or . These methods return an array of matched results, which is helpful if you need to extract values or analyze parts of the match.

    js const pattern = /^[+-]?\d+(.\d+)?$/; const input = "-42.8";

    // Using .test() console.log(pattern.test(input)); // true

    // Using .exec() const match = pattern.exec(input); if (match) { console.log("Matched:", match[0]); }

Note: When using or on a regular expression with the global () flag, consecutive calls on the same instance will continue searching from where the last match ended. For simple validations, avoid the flag to prevent unexpected results.


Metacharacters Used


  • ^ : Start of string

  • $ : End of string

  • \d : Any digit [0-9]

  • + : One or more of the previous

  • * : Zero or more of the previous

  • ? : Optional (zero or one)

  • \. : Escaped dot to match decimal

  • [,] : Comma literal

  • () : Grouping

  • [] : Character class


Examples


Example 1: Validating an Integer


const input = "250";
const pattern = /^\d+$/;

console.log(pattern.test(input)); // true

Try building your own patterns using the JavaScript Regex Tester.


Example 2: Validating a Decimal number


const input = "3.1415";
const pattern = /^\d+\.\d+$/;

console.log(pattern.test(input)); // true

You can further combine this with the Token Generator to auto-generate secure numbers.


Example 3: Detecting Signed and Unsigned Numbers


const input = "-0.99";
const pattern = /^[+-]?\d+(\.\d+)?$/;

console.log(pattern.test(input)); // true

Use this in combination with the JavaScript Regex Tester for rapid debugging.


Use Cases


  • Form Validation: Use regex to ensure users enter valid numbers in fields like age, quantity, and budget.

  • Financial Apps: Validate decimal precision in transactions and prices.

  • Data Cleaning: Filter out bad inputs before importing into analytics tools.

  • Auth Systems: Use regex to process numeric OTPs and login tokens generated via the Token Generator.


Combine With These Tools


Frequently asked questions

Can regex detect both positive and negative numbers?×
Yes, using ^[+-]?\d+(\.\d+)?$ allows both signed integers and decimals.
How do I validate a number that may or may not have decimals?+
Should I validate currency values using regex?+
Does \d match only digits?+
Can JavaScript regex validate formatted numbers like “1,000”?+