0

I use in my model following regular expression for getting a number that must to have a length 8. I do it this way:

validates_uniqueness_of :my_number, :with => /^[0-9]{8}$/, :message => "error message"

But this doesn't works me, if I set into the input "hahaha", I will get the "error message", if I set there 123, so I will get a success output, but that's wrong... I try to get a regular expression that will accepted always exact 8 digits...

Phrogz
  • 296,393
  • 112
  • 651
  • 745
user984621
  • 46,344
  • 73
  • 224
  • 412
  • 1
    You likely want a "validates" with both a regex *and* uniqueness. – Dave Newton Nov 29 '11 at 15:27
  • Note that `[0-9]` is [exactly equivalent](http://stackoverflow.com/questions/6998713/scanning-for-unicode-numbers-in-a-string-with-d) to the (shorter and more-self-describing) `\d` in Ruby regex. See also [the official docs](https://github.com/ruby/ruby/blob/trunk/doc/re.rdoc). – Phrogz Nov 29 '11 at 17:39

2 Answers2

4

Update: As @tadman points out in the comment, in Rails 3 you can combine validators:

validates :my_number, :uniqueness => true, :format => { :with => /^[0-9]{8}$/ }

Using old-style validation:

validates_uniqueness_of does not accept a with option, just validates_format_of does. So you might try:

validates_format_of :my_number, :with => /^[0-9]{8}$/, \
    :message => "8 digits, please."

To validate uniqueness you might want to add another constraint.

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
4

Probably:

validates_format_of :my_number, :with =>  /\A[0-9]{8}\Z/
validates_uniqueness_of :my_number
taro
  • 5,772
  • 2
  • 30
  • 34
  • 3
    In Rails 3+ this is expressed as `validates :my_number, :uniqueness => true, :format => { :with => /.../ }` using the new [validation methods](http://omgbloglol.com/post/392895742/improved-validations-in-rails-3). – tadman Nov 29 '11 at 15:50