In my case a very simple regex did the trick.
I needed to validate an user's input whether the input is a valid monetary value. I simply used-
/^[0-9]+(\.)?[0-9]*$/.test(number)
everything between //
is the Regular Expression.
/^
means the match starts from the beginning of the word and $/
means the match ends with the word. If you think the word can not start with the letter 0
then the expression would be like [1-9][0-9]*
[0-9]+
means the word must start with at least one number.
Note: *
means zero or more, +
means one or more and ?
means one or none.
Up to here the expression is /^[1-9][0-9]*$/
and this would validate only the integer numbers.
To test for a period (.) in the number we need to use \.
with the expression. .
is a special character which matches everything, \.
will only match the period.
Finally another character class [0-9]*
would match with zero or more digits.
Test Cases
/^[0-9]+(\.)?[0-9]$/.test("21.38a") // ==> false
/^[0-9]+(\.)?[0-9]$/.test("21.38") // ==> true
/^[0-9]+(\.)?[0-9]$/.test("y2781.68") // ==> false
/^[0-9]+(\.)?[0-9]$/.test("2781r.68") // ==> false