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
unless self.security_code.to_s.size == 3
errors.add(“security_code”, “should be 3 digits”)
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
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.