Joseph Paterson
Joseph Paterson

Reputation: 1493

Ruby ActiveRecord: validate format of an integer field

I'm trying to validate the format of a field in an ActiveRecord. I want this field to either be empty, or contain a sequence of digits only (it is containing an optional port number for a database connection). I'm currently trying this:

validates_format_of :port, with: /\A[0-9]*\Z/, message: 'Only numbers allowed'

but without luck. I've found that adding a required number by using for example {1, 6} sort of works, but makes the field mandatory.

Any advice?

Many thanks in advance,

Joseph.

Upvotes: 3

Views: 3194

Answers (4)

aallamand
aallamand

Reputation: 1

You can use this syntax as well

validates numericality: :only_integer

Upvotes: 0

Ricky Zein
Ricky Zein

Reputation: 557

You may want to try to validate the numericality of the field, like so:

validates_numericality_of :port, :only_integer => true

:only_integer will ensure that the value entered for :port is an integer.

Upvotes: 3

PinnyM
PinnyM

Reputation: 35533

You can also just add allow_blank: true

Upvotes: 1

James Chevalier
James Chevalier

Reputation: 10874

If you're looking to validate so that only numbers are allowed, then you should be able to use this:

validates :port, :numericality => {:only_integer => true}

Upvotes: 6

Related Questions