Forum: Ruby on Rails Validation of security code with leading zero

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
dodgyboz (Guest)
on 2007-07-23 16:01
(Received via mailing list)
Hi All,

I am trying to validate the security codes on payment cards but I am
having problems with leading zeros.

I initially started off with

validates_length_of :security_code, :is => 3

however this produced some unexpected results. My research suggested
that this was down to the fact that validates length of actually
validates the amount of bytes not the length of the string/number.

so then I changed my validation to

def validate
  unless self.security_code.to_s.size == 3
     errors.add("security_code", "should be 3 digits")
  end
end

however converting a number with a leading zero such as 056 to a
string drops the leading zero and becomes 56 which does not pass the
validation. (I think this is my best chance if I can keep the leading
zero)

finally i have tried

validates_format_of :security_code, :with => /\A[0-9][0-9]
[0-9]\Z/, :message => 'must be 3 digits'

but I am no regex expert and this does not appear to work either even
tough it seems like a rather simple regex. I have also tried other
variations on that regex such as /\d\d\d/ with no success.

Does any one know how I can keep the leading zero or validate the
length of this number in any other way. Surely this must be a common
problem but I am failing to find any solutions on the net.
unknown (Guest)
on 2007-07-23 16:18
(Received via mailing list)
Hi --

On Mon, 23 Jul 2007, dodgyboz wrote:

> however this produced some unexpected results. My research suggested
> that this was down to the fact that validates length of actually
> validates the amount of bytes not the length of the string/number.

Try making security code a string (i.e., string type in the database).
Then you should be able to do:

   validates_format_of :security_code, :with => /\A\d{3}\z/


David

--
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)
dodgyboz (Guest)
on 2007-07-23 16:36
(Received via mailing list)
Thanks removed_email_address@domain.invalid,

changing the column type in the db would appear to have been the over
site in this situation.

Once again thank you for the speedy responce.
This topic is locked and can not be replied to.