James Bush
James Bush

Reputation: 153

Validate Rails attribute presence but allow empty string

I want to validate a string attribute is not nil, but allow empty strings.

As in:

validates name: not_nil, allow_empty: true

Upvotes: 10

Views: 8027

Answers (3)

anthonyms
anthonyms

Reputation: 948

Alternatively

validates :name, presence: true, allow_blank: true

Upvotes: -2

James Bush
James Bush

Reputation: 153

To allow an empty string, but reject nil in an active record validation callback, use a conditional proc to conditionally require the presence of the attribute if it's not nil.

So the code looks like:

validates :name, presence: true, if: proc { name.nil? }

But you probably want to allow null. Then don't validate. Still check for presence? in code for nil or empty string.

Upvotes: 4

NullVoxPopuli
NullVoxPopuli

Reputation: 65183

you could also do:

validates :name, exclusion: { in: [nil] }

Upvotes: 8

Related Questions