This should cover all your cases.
/^(?:\d+(?:\.\d{1,2})?|\.\d{1,2})$/
Readable version
^
(?:
\d+
(?: \. \d{1,2} )?
| \. \d{1,2}
)
$
update after chat.
Seems the regex needs to operate on input in real time event handler,
like keypress paste etc..
To do that, it needs to be a progressive optional type of regex
to allow for partial matching, yet strip off invalid text.
That regex is
Find /^(\d+(?:\.\d{0,2})?|\.\d{0,2})?.*?$/
Replace "$1"
Readable version
^
( # (1 start)
\d+
(?:
\.
\d{0,2}
)?
| \. \d{0,2}
)? # (1 end)
.*?
$
When submitting the current entry a final validation regex could
be necessary, but maybe not.
That regex is something like this ^(?:\d+(?:\.\d{0,2})?|\.\d{1,2})$
The only possible invalidation will only ever be a single dot, or a blank
which was a valid current input but not valid in the final.
If it doesn't match, just set the input to 0 and go from there.
update
To limit rewriting the input text on every event, add a couple
of extra filter steps in the handler.
var RxFinalForm = /^(?:\d+(?:\.\d{0,2})?|\.\d{1,2})$/;
var RxRmvInvalid = /[^\d.]+/g;
var RxPartialForm = /^(\d+(?:\.\d{0,2})?|\.\d{0,2})?.*?$/;
function onlyNumber(element) {
ob = element.target;
var sContent = ob.textContent;
// Test if the current content is a valid Final Form.
// Note the ob.textContent does not need to be changed,
// thus preserving the caret position.
// -----------------------------------------------------
if ( RxFinalForm.test( sContent ) )
return; // No need to change anything, just return
// Remove any invalid characters ( non - dot/digit )
// --------------------------------------------------
sContent = sContent.replace( RxRmvInvalid, "" );
// Extract the Partial Form
// -------------------------
sContent = sContent.replace( RxPartialForm, "$1");
// Finally, if 'ob.textContent' does not equal 'sContent', change it.
// This will happens when an extra dot was enterred.
// ------------------------------------------------------------------
if ( ob.textContent !== sContent )
ob.textContent = sContent;
}
<input id="meters" type="number" name="meters" step="0.01" min="0" >
– Darbydarce