Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 861
Weblurk Avatar asked Feb 20 '14 12:02

Weblurk


1 Answers

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

like image 193
Tibos Avatar answered Sep 28 '22 07:09

Tibos