validates_format_of fails on empty field

I have a phone number field with the following validation:

validates_format_of :phone, :with => /^\d\d\d-\d\d\d-\d\d\d\d$/, :message => “The phone number must be of the format: ###-###-####”

It works fine, when the phone number is known. But, sometimes the phone number is not known, which causes an error. Is there an elegant way to validate the format only if the field in not empty? I’d rather not write conditional logic into all the forms that use this.

I've wondered about this too. Haven't done anything with it though. It's kind of hackish, but couldn't you do something like
with => /(^\d\d\d-\d\d\d-\d\d\d\d$|^$)/ to match the correct format OR an empty string?
I've just confirmed that that does work. Maybe I'll use that in my models. Thanks.

Larry Kelly wrote:

I have a phone number field with the following validation:

validates_format_of :phone, :with => /^\d\d\d-\d\d\d-\d\d\d\d
$/, :message => "The phone number must be of the format: ###-###-####"
  
It works fine, when the phone number is known. But, sometimes the
phone number is not known, which causes an error. Is there an elegant
way to validate the format only if the field in not empty? I'd rather
not write conditional logic into all the forms that use this.

Thanks for the responses, and the friendly help from this list. And thanks Jason for reminding me how incredibly powerful regular expressions are to those who know how to use them.

  • Larry