Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

374
Views
How to properly validate decimal values?

I am writing an input field sanitizer function that should check whether that input value is decimal or not.

Test cases:

  • 1234 - true
  • 12.34 - true
  • 0.123 - true
  • 000045 - true
  • 000.45 - false
  • .45685 - false
  • 5..454 - false
  • 55874. - true
  • 000000 - true
  • 0.0. - false

I don't want to show a validation error, I just want to prevent users from typing a wrong decimal value.

This regular expression /^[0-9]+\.?[0-9]+/ covers all the cases besides the 5th point. I guess here the only method to use is String.prototype.replace() in order to cut the unwanted wrong characters.

P.S. This validation is quite similar to HTML input type number native validation, except the 5th point, which is accepted as a valid number type.

UPDATED!

const rgx = /^[0-9]+\.?[0-9]+$/

const cases = [
  ["1234", true],
  ["12.34", true],
  ["0.123", true],
  ["000045", true],
  ["000.45", false],
  [".45685", false],
  ["5..454", false],
  ["55874.", true],
  ['000000', true],
  ['0.0.', false],
]

cases.forEach(([str, result]) => {
  const actual = rgx.test(str);
  if (actual !== result) {
    console.log(`Test case "${str}" failed, gave ${actual} but expected ${result}.`);
  }
});

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could test if the string does not start with 2 or more zeroes

^(?!00+\.)[0-9]+\.?[0-9]*$

Regex demo

Note that your pattern ^[0-9]+\.?[0-9]+$ matches at least 2 digits as only the comma is optional.

const rgx = /^(?!00+\.)[0-9]+\.?[0-9]*$/

const cases = ["1234",
  "12.34",
  "0.123",
  "000045",
  "000.45",
  ".45685",
  "5..454",
  "55874.",
  "000000",
  "0.0."
]

cases.forEach(s => console.log(`${s} --> ${rgx.test(s)}`));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!