Reputation: 2599
I am trying to validate dot and numbers.
Valid:
1.2.3
1.4.1
Invalid:
1.2.3.
1.2-3
1-2-3
I tried the following from another thread, it works with the valid, but it also passes the invalid with dash (-).
^\d+(.\d+)*$
Any betterment to the regex so it strict to validate only dot and digit?
Thanks
Upvotes: 3
Views: 1295
Reputation: 870
The dot matches all characters, you should use \.
^\d+(\.\d+)*$
But this would also validate any number without dot, when at least 1 dot should be present use:
(\d+\.)+\d+
Upvotes: 1
Reputation: 5492
If you need a variable number of dots and digits repeat digits & dots and put the last as only digit:
(\d+\.)+\d+
it matches 1.2.3 1.2.3.4 and so on
If you need fixed length of digits put the number of repetitions instead of the + operator
(\d+\.){2}\d+ #for 1.2.3
(\d+\.){1}\d+ #for 1.2
Upvotes: 2
Reputation: 32306
You need to escape the dot, which is otherwise "any character" in a regex:
^\d+(\.\d+)*$
Upvotes: 4
Reputation: 13460
use this regular expression ^\d+\.\d+\.\d+$
your misstake in dot, dot mean any symbol
Upvotes: 1