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.


Best Regards,
-Larry
“Work, work, work…there is no satisfactory alternative.”
— E.Taft Benson

Larry K. wrote:

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.


Best Regards,
-Larry
“Work, work, work…there is no satisfactory alternative.”
— E.Taft Benson

validates_presence_of doesn’t catch it when it’s empty?

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.

On Thu, 2006-12-28 at 08:07 -0800, Larry K. 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.


most of the validations provide for :allow_nil but I don’t see that
listed in the API for validates_format_of

I do see listed :if =>

which is probably what you are looking for

Craig

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

On 12/28/06, Jason N. [email protected] wrote:

I have a phone number field with the following validation:
Best Regards,
-Larry
“Work, work, work…there is no satisfactory alternative.”
— E.Taft Benson


Best Regards,
-Larry
“Work, work, work…there is no satisfactory alternative.”
— E.Taft Benson