dabadaba
dabadaba

Reputation: 9542

Rails validation: implicity presence validation

Let's say in my form there is a phone field, which has a format validation:

validates_length_of :phone, :is => 9

However, this is not a requiered field. It can be blank, but if filled in, then the format validation should start working.

How can I "disable" the implicit presence validation?

Upvotes: 1

Views: 66

Answers (1)

CDub
CDub

Reputation: 13354

You can use allow_blank to skip validation if the field isn't set:

validates :phone, :length => { :is => 9 }, :allow_blank => true

See the Rails validations guide for additional details.

So, for your explicit example:

validates_length_of :phone, :is => 9, :allow_blank => true

Will allow the phone field to be an empty string or nil, and skip the validation.

Upvotes: 2

Related Questions