JavaScript Notes
Master number validation in JavaScript using regex patterns. Learn integer, decimal, phone, currency validation with real examples and outputs.
Introduction
Number validation is one of the most common tasks in web development. Whether you're building a registration form, processing payment amounts, validating phone numbers, or accepting API data — you need to ensure the input is a valid number in the expected format.
Why does number validation matter?
- Form Inputs: Users can type anything — letters, symbols, spaces. You must validate before processing.
- API Data: External data sources may send malformed numbers that crash your calculations.
- Security: Invalid number inputs can lead to injection attacks or application crashes.
- User Experience: Instant feedback on invalid numbers improves form usability.
While JavaScript offers isNaN(), Number(), and parseInt(), these functions have quirky behaviors. For example, Number("") returns 0, and parseInt("123abc") returns 123. Regex gives you precise, predictable control over what constitutes a valid number in your specific context.
In this tutorial, you'll master every number validation pattern — from simple integers to complex currency formats — with clear explanations, code examples, and real-world applications.
Validation Patterns
1. Integer Only (Positive)
Matches: "0", "42", "99999" Rejects: "-5", "3.14", "12abc"
const positiveIntegerRegex = /^\d+$/;2. Integer (Positive + Negative)
Matches: "42", "-7", "0" Rejects: "3.14", "--5", ""
const integerRegex = /^-?\d+$/;3. Decimal / Float Number
Matches: "3.14", "-0.5", "42", "-100" Rejects: "3.", ".5", "1.2.3"
const decimalRegex = /^-?\d+(\.\d+)?$/;4. Phone Number (10 digits)
Matches: "9876543210", "1234567890" Rejects: "12345", "98765432101", "98-7654-3210"
const phoneRegex = /^\d{10}$/;5. Amount with Commas (Currency Format)
Matches: "1,000", "12,345,678.99", "100" Rejects: "1,00,000" (Indian format won't match), "1,23"
const currencyRegex = /^\d{1,3}(,\d{3})*(\.\d{2})?$/;6. Percentage (0-100)
Matches: "0", "50", "100", "99%" Rejects: "101", "-5", "1000%"
Code Examples
Example 1 — Positive Integer Validation
const regex = /^\d+$/;
console.log(regex.test("12345")); // pure digits
console.log(regex.test("0")); // zero is valid
console.log(regex.test("-5")); // negative sign
console.log(regex.test("12.34")); // decimal point
console.log(regex.test("")); // empty string
console.log(regex.test("12 34")); // space in betweentrue true false false false false
Example 2 — Integer with Negative Numbers
const regex = /^-?\d+$/;
console.log(regex.test("42")); // positive
console.log(regex.test("-7")); // negative
console.log(regex.test("0")); // zero
console.log(regex.test("--5")); // double minus
console.log(regex.test("-")); // only minus
console.log(regex.test("3.14")); // decimaltrue true true false false false
Example 3 — Decimal / Float Validation
const regex = /^-?\d+(\.\d+)?$/;
console.log(regex.test("3.14")); // valid decimal
console.log(regex.test("-0.001")); // negative decimal
console.log(regex.test("100")); // integer (also valid)
console.log(regex.test("3.")); // trailing dot — invalid
console.log(regex.test(".5")); // leading dot — invalid
console.log(regex.test("1.2.3")); // multiple dotstrue true true false false false
Example 4 — Phone Number Validation (10 Digits)
const phoneRegex = /^\d{10}$/;
console.log(phoneRegex.test("9876543210")); // valid 10 digits
console.log(phoneRegex.test("12345")); // too short
console.log(phoneRegex.test("98765432101")); // too long (11)
console.log(phoneRegex.test("987-654-3210")); // has dashes
console.log(phoneRegex.test("98765 43210")); // has spacetrue false false false false
Example 5 — Currency Amount with Commas
const currencyRegex = /^\d{1,3}(,\d{3})*(\.\d{2})?$/;
console.log(currencyRegex.test("1,000")); // one thousand
console.log(currencyRegex.test("12,345,678.99")); // millions with cents
console.log(currencyRegex.test("100")); // no commas needed
console.log(currencyRegex.test("1,00,000")); // Indian format — invalid
console.log(currencyRegex.test("1,23")); // wrong grouping
console.log(currencyRegex.test(",123")); // starts with commatrue true true false false false
Example 6 — Percentage Validation (0-100)
true true true true false false
Example 7 — Validation Function with Custom Messages
✅ "42" is a valid integer ✅ "-3.14" is a valid decimal ❌ "-5" is NOT a valid positive ✅ "9876543210" is a valid phone ❌ "12345" is NOT a valid phone
Example 8 — Extracting Numbers from Mixed Text
Found numbers: [ '123', '4', '1,299.99', '15' ] Pure integers: [ '123', '4', '1', '299', '99', '15' ] 123 → decimal test: true 4 → decimal test: true 1,299.99 → decimal test: false 15 → decimal test: true
Example 9 — Indian Phone Number with Country Code
true true true false false
Example 10 — Number Range Validation (1-999)
true true false false false true
Real-World Form Validation Example
Here's a complete form validation system that uses regex for all number fields:
Form Valid: true
Results: { age: true, phone: true, pincode: true, amount: true, percentage: true, year: true }
Bad Form Valid: false
Errors:
age: Age must be 1-120
phone: Enter valid 10-digit Indian mobile
pincode: Pincode must be exactly 6 digits
amount: Enter valid amount (max 2 decimals)
percentage: Enter 0-100
year: Enter valid year (1900-2099)🚫 Common Mistakes
Mistake 1 — Forgetting ^ and $ Anchors
// ❌ WRONG — matches "123" inside "abc123xyz"
const bad = /\d+/;
console.log(bad.test("abc123xyz")); // true — NOT what you want!
// ✅ CORRECT — requires ENTIRE string to be digits
const good = /^\d+$/;
console.log(good.test("abc123xyz")); // false — correct!true false
Why it happens: Without anchors, regex finds a match *anywhere* in the string. Always use ^...$ for validation.
Mistake 2 — Not Handling Empty Strings
// ❌ WRONG — /^\d*$/ matches empty string!
const bad = /^\d*$/;
console.log(bad.test("")); // true — empty is "valid"??
// ✅ CORRECT — use \d+ (one or more) to require at least one digit
const good = /^\d+$/;
console.log(good.test("")); // false — correctly rejects emptytrue false
Why it happens: * means "zero or more", so an empty string satisfies ^\d*$. Use + for "one or more".
Mistake 3 — Using \d vs [0-9] Without Understanding the Difference
true true true false
Best practice: Use \d for simple cases, [0-9] when combining with other character ranges for clarity.
Mistake 4 — Forgetting to Escape the Dot
// ❌ WRONG — unescaped dot matches ANY character
const bad = /^\d+.\d+$/;
console.log(bad.test("12X34")); // true — X matched by dot!
// ✅ CORRECT — escaped dot matches literal period only
const good = /^\d+\.\d+$/;
console.log(good.test("12X34")); // false — correctly rejects
console.log(good.test("12.34")); // true — matches decimaltrue false true
Why it happens: In regex, . is a metacharacter meaning "any character". Use \. for a literal dot.
Mistake 5 — Testing Numbers Instead of Strings
// ❌ WRONG — passing a number (not string) to test()
const regex = /^\d+$/;
console.log(regex.test(123)); // true — JS converts to "123"
console.log(regex.test(-5)); // false — converted to "-5"
console.log(regex.test(NaN)); // false — converted to "NaN"
console.log(regex.test(Infinity));// false — converted to "Infinity"
// ✅ CORRECT — always explicitly convert and check type
function isValidNumber(input) {
if (typeof input !== "string") return false;
return /^-?\d+(\.\d+)?$/.test(input);
}
console.log(isValidNumber("123")); // true
console.log(isValidNumber(123)); // false — not a stringtrue false false false true false
Why it happens: RegExp.test() calls toString() internally. Always validate the type before regex testing.
Mistake 6 — Not Trimming Whitespace
// ❌ Spaces will cause validation to fail
const regex = /^\d+$/;
console.log(regex.test(" 123 ")); // false — has spaces
console.log(regex.test("123\n")); // false — has newline
// ✅ Always trim user input before validation
const input = " 123 ";
console.log(regex.test(input.trim())); // true — after trimmingfalse false true
Mistake 7 — Allowing Leading Zeros When You Shouldn't
true true true false false
🎯 Key Takeaways
- Always use
^and$anchors for validation — without them, regex matches substrings and gives false positives.
- **Use
+not*** for required fields —\d*matches empty strings,\d+requires at least one digit.
- Escape the dot (
\.) when matching decimal points — an unescaped.matches any character.
- Trim input before testing — whitespace in user input causes unexpected validation failures.
- Validate type first — ensure the input is a string before applying regex; JavaScript auto-converts numbers to strings in
test().
- Choose the right pattern for your context — a phone number regex is very different from a currency amount regex. Don't use one generic pattern for all number types.
- Handle edge cases explicitly — empty strings, leading zeros, multiple decimal points, and negative signs all need specific pattern handling.
- Combine regex with logical checks when ranges matter — regex alone can't easily validate "number between 1 and 100". Use regex for format + code for range.
- Test with boundary values — always test your regex with
"","0","-0","999999999", and unexpected inputs like"1e5"or"NaN".
- Keep patterns readable — use named variables, add comments, and break complex patterns into smaller validated parts rather than writing one massive unreadable regex.
❓ Interview Questions
Q1: How do you validate that a string contains ONLY digits using regex?
Answer: Use /^\d+$/ — the ^ anchor asserts start of string, \d+ matches one or more digits, and $ asserts end of string. This ensures the entire string consists of only digits with no other characters.
const regex = /^\d+$/;
console.log(regex.test("12345")); // true
console.log(regex.test("12a45")); // falsetrue false
Q2: What's the difference between /\d+/ and /^\d+$/ for validation?
Answer: /\d+/ finds digits *anywhere* in the string — "abc123xyz".match(/\d+/) returns "123". It's a search pattern. /^\d+$/ ensures the *entire* string from start to end is all digits — it's a validation pattern. For form validation, always use anchored patterns.
console.log(/\d+/.test("hello123world")); // true (finds 123)
console.log(/^\d+$/.test("hello123world")); // false (entire string isn't digits)true false
Q3: Write a regex to validate a price like "1,234,567.89" (US currency format).
Answer: /^\d{1,3}(,\d{3})*(\.\d{2})?$/ — starts with 1-3 digits, followed by zero or more groups of comma + 3 digits, optionally ending with dot + exactly 2 decimal digits.
const priceRegex = /^\d{1,3}(,\d{3})*(\.\d{2})?$/;
console.log(priceRegex.test("1,234,567.89")); // true
console.log(priceRegex.test("1234567.89")); // false (missing commas)
console.log(priceRegex.test("1,234.5")); // false (1 decimal digit)true false false
Q4: How would you validate that a number is between 1 and 100 using only regex?
Answer: /^(100|[1-9]\d?)$/ — this matches either exactly "100", or a number starting with 1-9 followed by an optional digit. This covers 1-9 (single digit) and 10-99 (two digits) and exactly 100.
true true true false false
Q5: Why does Number("") return 0 but regex correctly rejects empty strings?
Answer: JavaScript's Number() conversion treats empty string as 0 (a language quirk from the spec). Similarly, Number(" ") and Number("\t") return 0. Regex /^\d+$/ correctly rejects empty strings because + requires at least one character match. This is why regex is preferred for strict validation over type coercion methods.
// JavaScript quirks
console.log(Number("")); // 0 — misleading!
console.log(Number(" ")); // 0 — also misleading!
console.log(isNaN("")); // false — says it IS a number!
// Regex is strict and predictable
console.log(/^\d+$/.test("")); // false — correctly rejects
console.log(/^\d+$/.test(" ")); // false — correctly rejects0 0 false false false
📝 FAQ
1. Should I use regex or parseInt()/Number() for validation?
Use regex when you need strict format validation (e.g., "exactly 10 digits", "number with 2 decimal places"). Use Number() or parseFloat() when you need to actually compute with the value. Often, the best approach is: validate format with regex first, then convert with Number() for calculations.
2. How do I validate decimal numbers that allow both "5" and "5.0" formats?
Use /^-?\d+(\.\d+)?$/. The (\.\d+)? part makes the decimal portion optional, so both "5" (integer) and "5.0" (decimal) pass. If you want to also allow ".5" (no leading digit), use /^-?(\d+\.?\d*|\.\d+)$/.
3. Does \d in JavaScript match Unicode digits (like Arabic numerals ١٢٣)?
No. In JavaScript's default regex mode, \d is equivalent to [0-9] — it only matches ASCII digits 0 through 9. If you need to match Unicode digits, use the Unicode flag: /^\p{Nd}+$/u (where \p{Nd} matches any Unicode decimal digit).
4. What's the performance impact of using regex for number validation?
Regex for simple number patterns is extremely fast — typically nanoseconds per test. It's compiled once and reused. For form validation, the performance cost is negligible. However, avoid creating regex inside loops (new RegExp(...) on every iteration) — define the pattern outside and reuse it.
5. How can I validate numbers in scientific notation like "1.5e10"?
Use /^-?\d+(\.\d+)?([eE][+-]?\d+)?$/. This adds an optional exponent part: e or E, followed by optional + or -, followed by one or more digits.
true true false
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Number Validation with Regex — Complete Patterns & Examples 2026.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, regex, number, validation
Related JavaScript Master Course Topics