4

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.

1

4 Answers 4

6

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}
Sign up to request clarification or add additional context in comments.

1 Comment

That works like a charm, thanks! Added allow_blank: true to complete the validation.
3

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.

Comments

1

You can also just add allow_blank: true

Comments

1

You can use this syntax as well

validates numericality: :only_integer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.