0

I would like to validates format of a decimal, which need to be like : 0 or 0.5 or 1 or 1.5 ... Also, I must be able to accept "," or "." (for users of differents countries)

Could you help me please ? I'm not really good with regular expressions...

Thanks.

eluus
  • 213
  • 1
  • 13
  • Will you be matching negative numbers? – rvalvik Mar 13 '13 at 15:00
  • In my model, I write this : `validates_format_of :default_duration, :with => /[0-9][0-9]*([.,][0-9][0-9]*)*/, :message => "Wrong format" ` ? – eluus Mar 13 '13 at 15:00
  • possible duplicate of [Decimal or numeric values in regular expression validation](http://stackoverflow.com/questions/2811031/decimal-or-numeric-values-in-regular-expression-validation) – stema Mar 13 '13 at 15:00
  • No negative numbers, only integer or x and a half. – eluus Mar 13 '13 at 15:01
  • [Regular expression validator accept decimal numbers 0 or 5](http://stackoverflow.com/questions/12225931/regular-expression-validator-accept-decimal-numbers-0-or-5?rq=1) – stema Mar 13 '13 at 15:25

3 Answers3

2

You can use this regex

 /^\d+([.,]\d+)?$/

^ is start of the string

$ is end of the string

^,$ is essential else it would match anywhere in between..for example the above regex without ^,$ would also match xyz344.66xyz

\d matches a single digit

+ is a quantifier that matches 1 to many preceding character or group..so \d+ means match 1 to many digits

? means match preceding character or group optionally that is 0 to 1 time

Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • Thanks for the information. Which validator do you use ? I tried validates_format_of but it doesn't works... – eluus Mar 13 '13 at 15:07
  • @user2072365 [this](http://stackoverflow.com/questions/3456785/ruby-regexp-match-string-exactly) can help you... – Anirudha Mar 13 '13 at 15:08
  • I tried `if self.default_duration =~ /^\d+([.,]\d+)?$/` but I always have an error, even with just an integer. – eluus Mar 13 '13 at 15:24
0

This regexp could help:

 ^\d+[,\.]?\d+$
Michael Malinovskij
  • 1,422
  • 8
  • 22
0

/^\d+((\.|\,)\d)?$/

Matches 12, 12,0, 12.0. If you wanted to add many trailing digits, /^\d+(\.|\,)?\d+$/

varatis
  • 14,494
  • 23
  • 71
  • 114