Ruby ActiveRecord: validate format of an integer field

activerecord, ruby-on-rails

Solution

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}

Problem

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.

Original source