I am writing an input field sanitizer function that should check whether that input value is decimal or not.
Test cases:
1234
- true12.34
- true0.123
- true000045
- true000.45
- false.45685
- false5..454
- false55874.
- true000000
- true0.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!
CodePudding user response:
You could test if the string does not start with 2 or more zeroes
^(?!00 \.)[0-9] \.?[0-9]*$
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)}`));