Weird validation problem

I have a field called Fax in my model. I store it as a 10-digit number
with no other characters but I display it as a nicely formatted phone
number. I have a validation on it like this:

validates_format_of :Fax,
:message => ‘number should be formatted using (XXX) XXX-XXXX’,
:with => /^(\d{3})\ ?\d{3}-\d{4}$/

If I put 1234567890 (10 digits) in my field, the validation doesn’t
fail. I’m guessing it has something to do with my getter and setter and
when the validation code is actually run. Is the field being saved and
then re-retrieved, and formatted “correctly” by my getter before the
validation call happens? That’s my guess.

Here is the getter:

public
def Fax
fax = read_attribute(:FAX)
unless fax.nil?
fax.gsub!(/(/, ‘’)
fax.gsub!(/)/, ‘’)
fax.gsub!(/-/, ‘’)
end

if (fax =~ /^\d{10}$/)
  sprintf("(%d) %d-%d", fax[0,3], fax[3,3], fax[6,4])
else
  fax
end

end

Here is the setter:
public
def Fax=(fax)
unless fax.nil?
fax.gsub!(/(/, ‘’)
fax.gsub!(/)/, ‘’)
fax.gsub!(/-/, ‘’)
fax.gsub!(/\s/, ‘’)
end
write_attribute(:FAX, fax)
end

Thanks,
Wes

Wes G. wrote:

If I put 1234567890 (10 digits) in my field, the validation doesn’t
fail. I’m guessing it has something to do with my getter and setter and

“doesn’t fail” means that the validation doesn’t catch the error and
treat it as such.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs