Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 315
Joseph Paterson Avatar asked Nov 01 '25 10:11

Joseph Paterson


2 Answers

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}
like image 179
James Chevalier Avatar answered Nov 04 '25 01:11

James Chevalier


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.

like image 40
Ricky Zein Avatar answered Nov 04 '25 00:11

Ricky Zein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!