Here's an alternative way. I'm using the oninput event that is triggered on every value change by user (not only key presses). I'm saving the last valid value and restoring it whenever the new value is invalid.

<input type="text" id="test1" oninput="validateNumber(this);" />
<script>
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
  if (validNumber.test(elem.value)) {
    lastValid = elem.value;
  } else {
    elem.value = lastValid;
  }
}
</script>

In contrast to most other answers here this works flawlessly with all input techniques like drag'n'drop, copy'n'paste etc. It also supports special control keys like Ctrl+a (for selecting contents), Pos1, End and so on.

Answer from Hugo G on Stack Overflow
🌐
RegExr
regexr.com › 3eqpa
RegExr: only digits and one decimal
RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp). Supports JavaScript & PHP/PCRE RegEx.
🌐
UI Bakery
uibakery.io › regex-library › numbers-only
Numbers Only Regex: Match Digits Only in JavaScript and Python
If your input contains other text and you want to extract numeric parts instead of validating the entire value, use a different regex: ... Use ^\d+$ for validation and \d+ for extraction. They solve different problems. ... This pattern finds digits anywhere inside a string, so it would match abc123xyz. If you need a digits-only value, use: ... This page is for integers written as digits only. It will not match: ... If you need signed numbers, decimals, currency values, or formatted numbers, use a different pattern.
🌐
Regex Tester
regextester.com › 104022
Whole Numbers + Decimal Numbers - Regex Tester/Debugger
Matches Whole numbers as well as decimal numbers. https://digitalfortress.tech/tricks/top-15-commonly-used-regex/ ... Url checker with or without http:// or https:// Match string not containing string Check if a string only contains numbers Only letters and numbers Match elements of a url date format (yyyy-mm-dd) Url Validation Regex | Regular Expression - Taha Match an email address Validate an ip address nginx test Extract String Between Two STRINGS special characters check match whole word Match anything enclosed by square brackets.
🌐
Medium
medium.com › @matthewmain › regex-javascript-edition-14c531ed572e
Regex, JavaScript Edition. The quickest way to use regular… | by Matthew Main | Medium
December 19, 2018 - Let’s start by testing an example ... string you’re checking contains only the designated pattern by wrapping the regex in ^ and $: ... Accounting for commas is a little more complex....
🌐
Laserfiche Answers
answers.laserfiche.com › questions › 196385 › Regex-to-Capture-Amount-Only-with-Decimal
Regex to Capture Amount Only with Decimal - Laserfiche Answers
March 4, 2022 - I believe something like this would do it, at least up to 999,999.99, which seems likely it's good enough for a discount :). (you could also add another "(\d{1,3})?,?" in front to capture up to 999 million) Discount Amount:\s*?(\d{1,3})?,?(\d{1,3})?(\.\d\d) But let's break it down a bit: The first part, "Discount Amount:", is anchoring text and helps you verify you're capturing the correct number. This is followed by \s*, which means "any amount of whitespace". Then we have "(\d{1,3})?", which says there is an optional set of 1-3 digits that we want to capture. This would be capturing the thousands block (e.g., values between 1,000.00 and 999,999.99).
🌐
CodeProject
codeproject.com › Questions › 426944 › regular-expression-which-allow-both-decimals-as-we
https://www.codeproject.com/Questions/426944/regul...
Do not try and find the page. That’s impossible. Instead only try to realise the truth - For those who code; Updated: 1 Jul 2007
🌐
TutorialsPoint
tutorialspoint.com › How-to-validate-decimal-numbers-in-JavaScript
How to validate decimal numbers in JavaScript?
October 31, 2022 - Patterns contain the characters ... to validate decimal numbers in JavaScript ? var decimal= <Decimal number here>; var regex= /^[-+]?[0-9]+\.[0-9]+$/; var isValidated=decimal.test(regex);...
🌐
Quora
quora.com › How-do-you-construct-a-regex-to-accept-15-digits-with-or-without-decimal-JavaScript-angular-regex-development
How to construct a regex to accept 15 digits with or without decimal (JavaScript, angular, regex, development) - Quora
How do you get a decimal number after @ with regex (regex, development)? How do I check if a string is a valid date using regular expression or regex in JavaScript? How do you construct a regex expression with white space not allowed at first and allowed in the middle (angular, regex, development)? How do you delete a custom HTML tag from a string by using regex (JavaScript, regex, development)? How do you construct a regex to not allow only ...
Find elsewhere
🌐
Ecorp
lawrence.ecorp.net › inet › samples › regexp-validate2.php
JavaScript Regular Expression - Frames
These differ only in the addition of test, (\.\d+) for a decimal point and decimals. NOTE: the if a decimal point is present it must be followed by at least one digit in each example. The third example, limiting the number of decimals, is useful for currencies.
Top answer
1 of 12
54

Try the following expression: ^\d+\.\d{0,2}$ If you want the decimal places to be optional, you can use the following: ^\d+(\.\d{1,2})?$

EDIT: To test a string match in Javascript use the following snippet:

var regexp = /^\d+\.\d{0,2}$/;

// returns true
regexp.test('10.5')
2 of 12
53

Positive decimals only

/^\d+(\.\d{1,2})?$/

Negative or positive decimals

/^-?\d+(\.\d{1,2})?$/

Demo

var regexp = /^\d+(\.\d{1,2})?$/;

console.log("POSITIVE ONLY");
console.log("'.74' returns " + regexp.test('.74'));
console.log("'7' returns " + regexp.test('7'));
console.log("'-4' returns " + regexp.test('-4'));
console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'115.25' returns " + regexp.test('115.25'));
console.log("'-120.56' returns " + regexp.test('-120.56'));
console.log("'1535.803' returns " + regexp.test('1535.803'));
console.log("'153.14.5' returns " + regexp.test('153.14.5'));
console.log("'415351108140' returns " + regexp.test('415351108140'));
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));

regexp = /^-?\d+(\.\d{1,2})?$/;

console.log("\n");
console.log("POSITIVE OR NEGATIVE");
console.log("'.74' returns " + regexp.test('.74'));
console.log("'7' returns " + regexp.test('7'));
console.log("'-4' returns " + regexp.test('-4'));
console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'115.25' returns " + regexp.test('115.25'));
console.log("'-120.56' returns " + regexp.test('-120.56'));
console.log("...");


Explanation

  1. / / : the beginning and end of the expression
  2. ^ : whatever follows should be at the beginning of the string you're testing
  3. \d+ : there should be at least one digit
  4. ( )? : this part is optional
  5. \. : here goes a dot
  6. \d{1,2} : there should be between one and two digits here
  7. $ : whatever precedes this should be at the end of the string you're testing

If you also want to support negative decimals, you just need to add -? right after the ^, which means that an optional minus sign is allowed there as well.


Tip

You can use regexr.com or regex101.com for testing regular expressions directly in the browser!

🌐
Regex Pal
regexpal.com
Whole Numbers + Decimal Numbers - Regex Pal
Matches Whole numbers as well as decimal numbers. https://digitalfortress.tech/tricks/top-15-commonly-used-regex/ ... Url checker with or without http:// or https:// Match string not containing string Check if a string only contains numbers Only letters and numbers Match elements of a url date format (yyyy-mm-dd) Url Validation Regex | Regular Expression - Taha Match an email address Validate an ip address nginx test Extract String Between Two STRINGS special characters check match whole word Match or Validate phone number Match anything enclosed by square brackets.
🌐
Medium
medium.com › @jnesong › phase-2-the-questions-continue-efd38f015aba
Regex to validate for decimal numbers in a text type form input. | by Jenny Chau Song | Medium
March 29, 2022 - A quick comparison of how different languages use RegExp= {Treehouse article) /> </Route> Thank you for reading ☺️ · JavaScript · React · Form Validation · Regular Expressions · Decimal Number Validation · 16 followers · ·17 following · 🩺 → 👩🏻‍💻 ·
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-restrict-input-box-to-allow-only-numbers-and-decimal-point-javascript
How to Restrict Input to Numbers and Decimals in JavaScript? - GeeksforGeeks
September 12, 2024 - Status Updates: The script updates ... or invalid based on the regex check. Example : This example uses the approach discussed above using JavaScript. ... <!DOCTYPE HTML> <html> <head> <title> How to restrict input box to allow only numbers and decimal point JavaScrip...
🌐
ServiceNow Community
servicenow.com › community › itsm-forum › validation-regex-for-numbers-and-as-well-allows-decimal-values › td-p › 2734103
Validation Regex for Numbers and as well allows decimal values ?
November 16, 2023 - Hello @Deepika61, Please refer to the below link: https://www.servicenow.com/community/developer-forum/regex-for-decimal-validation/m-p/2103267 · Mark my correct and helpful, if it is helpful and please hit the thumbs-up button to mark it as the correct solution. Thanks & Regards, Abbas Shaik ... I have created a field %Complete where it should allow only numbers from 0 to 100 in Incident Management forum 2 weeks ago