How to check if a string contains only numbers, comma and regex periods in javascript?

I have an input field in which I will accept numbers, commas and periods. How to check if a string is consistent with these rules?

I tried the following:

var isValid = /([0-9][,][.])$/.test(str);

but it does not work. the variable isValid is always false.

+3
source share
2 answers

In your regex, one character is expected from the first class (0-9), then one from the second class (comma), then one from the last class (period). Instead, you want any number of characters (*) from the class to contain numbers, commas, and periods ( [0-9,.]). Also, you do not need parentheses:

var isValid = /^[0-9,.]*$/.test(str);

DEMO (and explanation): http://regex101.com/r/yK6oF4

+12

var regex = "[- +]? [0-9].? [0-9]"

. 1 - true

1.1 - true

1.1.1 - false

1.a - false

0

All Articles