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.
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}
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.
You can also just add allow_blank: true
You can use this syntax as well
validates numericality: :only_integer
Related
I am trying to validate the entry a user makes in an amount field.
The field is amount_money
This field is a string which is validated on form submission
monetize :amount, :as => :amount_money
validates :amount, numericality: {only_integer: true}
validates :amount_money, numericality: {greater_than_or_equal_to: 0}
validate :amount_money_within_limit
validate :is_a_valid_number
I want to ensure there are no letters or symbols and that the amount is in an acceptable range.
the code to do this is
def amount_money_within_limit
if amount_money && amount_money.cents > 10_000_00
errors.add(:amount_money, 'cannot exceed $10,000.')
end
if amount_money && amount_money.cents < 1_00
errors.add(:amount_money, 'Problem with Amount')
end
end
this works great for input numbers, of numbers and letters, of letters, of special characters but
If I try Bob - the validation kicks in
but if I try BBob - the validation is bypassed.
If the input contains 2 Capital letters next to each other - it fails.
I've tried a downcase - but that doesn't suit as the field is monetized (money gem) - and the downcase screws up if there is valid input.
If the input to the field contains two uppercase letters - all the validations are bypassed So something like AA is not caught by any on the above validations
Why don't you use regular expressions? Something like this:
def is_a_valid_number? amount_money
amount_money =~ /\d+/
end
It seems you have put 1 validation on the wrong field, you should've put validations only on amount field (your real db field), and not on the amount_money which is automagical field from rails-money gem. I'll apply their documentation on numerical validations to your case:
monetize :amount,
:numericality => {
:only_integer => true,
:greater_than_or_equal_to => 1_00,
:less_than_or_equal_to => 10_000_00
}
You won't need any other custom validations with this setup.
In my Rails app college students with either #berkeley.edu or #uw.edu email addresses can register. I have the regex for validating both ready but since I need to check the email address the user enters to see which one it matches I think I need to create one regex, but I don't know how. Here are my two regex's:
berkeley_regex = /\A[\w+\-.]+#berkeley\.edu\z/i
uw_regex = /\A[\w+\-.]+#uw\.edu\z/i
And my validate:
validates :email, :presence => true, :uniqueness => true, :format => {:with => berkeley_regex}
Now, what would the regex to check against both but only match against one look like?
Can't you just validate against something like /\A[\w+\-.]+#(berkeley|uw)\.edu\z/i and be done with it? If you really need to later determine which it is, make a method that just checks the back part, or returns the match, or whatever...
First I think your regex should be changed from [\w+\-.] to [\w+\-\.]
The validation could be
validates :email, format: { with: "\A#{berkely_regex}|#{uw_regex}\z/i" }
but you'll need to remove the flags ( \A, \z, /i ) from the vartiables
I'm trying to customize my error messages by modifying en.yml.
en:
errors:
messages:
blank: "This is a required field."
And now, every empty field that has the validates presence: true validator shows this new message.
I want to find a list of messages types to modify. For example, how can I customize the numericality validator message? Or the greater_than validator?
Any suggestions where to find this?
Here is a list of the messages you can customize in the en.yml file:
validates_acceptance_of
`:accepted` (“must be accepted”)
validates_associated
`:invalid` (“is invalid”)
validates_confirmation_of
`:confirmation` (“doesn’t match confirmation”)
validates_exclusion_of
`:exclusion` (“is reserved”)
validates_format_of
`:invalid` (“is invalid”)
validates_inclusion_of
`:inclusion`(“is not included in the list”)
validates_length_of
`:too_short` (“is too short (minimum is {{count}} characters)”)
`:too_long` (“is too long (maximum is {{count}} characters)”)
validates_length_of (with :is option)
`:wrong_length` (“is the wrong length (should be {{count}} characters)”)
validates_numericality_of
`:not_a_number` (“is not a number”)
validates_numericality_of (with :odd option)
`:odd` (“must be odd”)
validates_numericality_of (with :even option)
`:even` (“must be even”)
validates_numericality_of (with :greater_than option)
`:greater_than` (“must be greater than {{count}}”)
validates_numericality_of (with :greater_than_or_equal_to option)
`:greater_than_or_equal_to` (“must be greater than or equal to {{count}}”)
validates_numericality_of (with :equal_to option)
`:equal_to` (“must be equal to {{count}}”)
validates_numericality_of (with :less_than option)
`:less_than` (“must be less than {{count}}”)
validates_numericality_of (with :less_than_or_equal_to option)
`:less_than_or_equal_to` (“must be less than or equal to {{count}}”)
validates_presence_of
`:blank` (“can’t be blank”)
validates_uniqueness_of
`:taken` (“has already been taken”)
Further to Serg's answer, you can find the list of keys for built-in validators here:
http://guides.rubyonrails.org/i18n.html#error-message-interpolation
It finds error message in a chain of namespaces. Consider a User model with a validation for the name attribute like this:
class User < ActiveRecord::Base
validates :name, presence: true
end
The key for the error message in this case is :blank. Active Record will look up this key in the namespaces:
activerecord.errors.models.[model_name].attributes.[attribute_name]
activerecord.errors.models.[model_name]
activerecord.errors.messages
errors.attributes.[attribute_name]
errors.messages
Thus, in our example it will try the following keys in this order and return the first result:
activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank
Hope it will help. Thanks
To add on to #MikeL answer, which only shows the keys, the full list with the keys and interpolated messages can be found here at rails very own github repository.
I am currently validating my model using this code:
validates :price, :presence => true, :numericality => {:greater_than => 0}
This works fine, except that when I do not enter any value in this field, I get 2 errors - both "Price can't be blank" and "Price is not a number".
I can understand why this happens - clearly it is failing both tests. But i'm wondering if there is a way to ge the validation to stop after one test, since there is no point testing if the number is > 0 if there is no number at all?
Thanks!
Edit: For clarity, I don't want to allow the field to be blank, I just don't want the numericality test to run if it is blank, to avoid 2 error messages for what is really 1 error.
Not sure if it will work, but you can try:
validates :price, :presence => true, :numericality => {:greater_than => 0, :allow_blank => true }
Does rails have a validator like validates_numericality_of for boolean or do I need to roll my own?
Since Rails 3, you can do:
validates :field, inclusion: { in: [ true, false ] }
I believe for a boolean field you will need to do something like:
validates_inclusion_of :field_name, :in => [true, false]
From an older version of the API: "This is due to the way Object#blank? handles boolean values. false.blank? # => true"
I'm not sure if this will still be fine for Rails 3 though, hope that helped!
When I apply this, I get:
Warning from shoulda-matchers:
You are using validate_inclusion_of to assert that a boolean column
allows boolean values and disallows non-boolean ones. Be aware that it
is not possible to fully test this, as boolean columns will
automatically convert non-boolean values to boolean ones. Hence, you
should consider removing this test.
You can use the shorter version:
validates :field, inclusion: [true, false]
Extra thought. When dealing with enums, I like to use a constant too:
KINDS = %w(opening appointment).freeze
enum kind: KINDS
validates :kind, inclusion: KINDS
Answer according to Rails Docs 5.2.3
This helper (presence) validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.
Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:
validates :boolean_field_name, inclusion: { in: [true, false] }