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.
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.
You are passing 1 char each time to the myfunction function, so you cannot check the whole value with /^[0-9]+([.][0-9]+)?$/ regex to make sure your format is adhered to.
Check if you input digits, or only allow typing a dot if there is no dot in the input field yet:
<input type="text" id="test" onkeypress="return myfunction(event);" />
<script>
function myfunction(e) {
return e.charCode === 0 || ((e.charCode >= 48 && e.charCode <= 57) || (e.charCode == 46 && document.getElementById("test").value.indexOf('.') < 0));
}
</script>
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')
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
/ /: the beginning and end of the expression^: whatever follows should be at the beginning of the string you're testing\d+: there should be at least one digit( )?: this part is optional\.: here goes a dot\d{1,2}: there should be between one and two digits here$: 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!
Updated answer:
RegExp -
^(?:0|[1-9]\d+|)?(?:.?\d{0,2})?$
Explanation at regex101:

Original answer:
fiddle Demo
RegExp -
^(\d+)?([.]?\d{0,2})?$
Explanation
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Here is a suggestion : /^((\d|[1-9]\d+)(\.\d{1,2})?|\.\d{1,2})$/.
Allows : 0, 0.00, 100, 100.1, 100.10, .1, .10...
Rejects : 01, 01.1, 100., .100, ....
Check length via lookahead.
↓ ↓ CHANGE THESE PARAMETERS
/^(?=(.[.]?){1,7}$)\d*([.]\d{1,2})?$/
|---------------| LOOK-AHEAD TO CHECK LENGTH
|-| INTEGER PORTION OF NUMBER
|-----------| OPTIONAL DECIMAL PORTION OF NUMBER
This is more easily scalable to variations of the problem such as "up to seven total digits with up to four decimal places" than other solutions are. Just replace the two characters pointed to by "CHANGE THESE PARAMETERS".
Pretty sure this will do it for ya:
^(\d{1,5}\.\d{2}|\d{1,6}\.\d|\d{1,7})$
Anything that is 5.2 or 6.1 or 7 digits (max number of characters)
need
/^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/
See the regex demo
Details
^- start of string(?:\d{1,3}(?:,\d{3})*|\d+)- Either of:\d{1,3}(?:,\d{3})*- 1 to 3 digits followed with 0+ sequences of a,and 3 digits|- or\d+- 1 or more digits
(?:\.\d+)?- an optional sequence of.and 1+ digits$- end of string.
var strs = [',,,,', '111', '11,111', '11,111.0', '111111'];
var re = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
for (var s of strs) {
console.log(s + " => " + re.test(s));
}
This is a very simple general solution, without any assumptions about how many digits are needed.
/^\d[\d,]*(\.\d+)?$/
[\d,] will match digits or commas.
You could make the regex more complicated if you really need it to be more specific.