10

I have an input field that I will only accept numbers, commas and periods. How can I test if the string is valid according to these rules?

I have tried the following:

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

but it's not working. isValid variable is always false.

Weblurk
  • 5,763
  • 16
  • 52
  • 101

2 Answers2

24

Your regexp expects one character from the first class (0-9), then one from the second class (comma) then one from the last class (dot). Instead you want any number of characters (*) from the class containing digits, commas and dots ([0-9,.]). Also, you don't need the parenthesis:

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

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

Tibos
  • 26,262
  • 4
  • 43
  • 59
  • Thanks, I will mark this an answer as soon as I can. Just a question. How do I add blank spaces to the allowed characters? would it be [0-9,. ]? (Notice the space after period) – Weblurk Feb 20 '14 at 12:29
  • @Weblurk Yes. You can use the tool i linked to try stuff out. The explanation of the regexp is most useful. – Tibos Feb 20 '14 at 12:44
0

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

This works perfect for decimal number & Integer. e.g. 1 - true

1.1 - true

1.1.1 - false

1.a - false

Justin Patel
  • 883
  • 8
  • 5