What is the best way to validate a cost/price input by a user, validation rules below:
Examples of formats allowed .23, .2, 1.23, 0.25, 5, 6.3 (maximum of two digits after decimal point)
Minimum value of 0.01
Maximum value of 9.99
Check the price and verify the format
#rails 3
validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ }, :numericality => {:greater_than => 0, :less_than => 10}
#rails 2
validates_numericality_of :price, :greater_than => 0, :less_than => 10
validates_format_of :price, :with => /\A\d+(?:\.\d{0,2})?\z/
For client side validations you can use a jQuery plugin like this one that allows you to define different valid formats for a given input.
For server side validations and according to this question/answer maybe you should use a decimal column for price in which you can define values for precision and scale, scale solves the two digits after decimal point restriction.
Then to validate the numericality, minimum and maximum value you can use the next validation method:
validates_numericality_of :price, :greater_than => 0, :less_than => 10
You can build custom validations.Lets say, for example the second case:
validate :price_has_to_be_greater_than_minimum
def price_has_to_be_greater_than_minimum
errors.add(:price, "price has to be greater than 0.01") if
!price.blank? and price > 0.01
end
More on this, in the Rails Guides, here.
Related
This is my model:
class Garment
include ActiveAttr::Model
#include ActiveModel::Validations
extend CarrierWave::Mount
attribute :title
mount_uploader :image, ImageUploader
alpha_numeric_regix = /\A[a-zA-Z0-9-_]\z/
validates :title, :presence => true,
:length => { :minimum => 5, :maximum => 30 },
:format => {
:with => alpha_numeric_regix,
:message => "must contain letters, dashes and underscores only"
}
How ever my actual form keeps telling me the validation has failed when I use purely letters and spaces e.g. VA Yellow Top
Rubular: http://rubular.com/r/ynd3DOWCxe
What could the problem be. In rubular using two letter "VA" fails validation as well.
What could be going on?
/\A[a-zA-Z0-9-_]\z/ + when I use purely letters and spaces - there is no space in your regex, should be
`/\A[a-zA-Z0-9\-_\ ]+\z/`
I have an input (it's text input) where users can set up the price.
The problem is, that users can sometimes set up the price like this:
9
9.99
9,99
$9.99
What's the best way to validate this input? I am running the app on Heroku (= PostgreSQL database), the data type column is decimal.
Rails 4 complains about using $ and ^, so use:
validates :price, :presence => true,
:format => { :with => /\A(\$)?(\d+)(\.|,)?\d{0,2}?\z/ }
Just trying to save people time ;-)
Try something like below. It matches all you examples.
validates :price, :presence => true,
:format => { :with => /^(\$)?(\d+)(\.|,)?\d{0,2}?$/ }
Hi I have a model called users, and they have a cell phone attribute that must be entered as a 12 digit string leading with "+". I want to validate that the attribute they entered from a form is in fact in the correct format. Example "+11234567890" should save to the model, but "1232h" will not.
This is what I have in my model, but it does not work:
validates :cell, :format => { :with => /^[-+]?[0-9]+$/,
:message => "Only numbers allowed" }, :length => { :is => 10 }
Try this:
validates :cell, :format => { :with => /\A(\+1)?[0-9]{10}\z/, :message => "Not a valid 10-digit telephone number" }
I think the problem is that you're trying to do two different kinds of validations on a single validates line. The above combines the length constraint with the number constraint, and allows the variable +/- without messing up the length constraint.
I am new at Ruby on Rails.
I was trying to validate format of one of the attribute to enter only float.
validates :price, :format => { :with => /^[0-9]{1,5}((\.[0-9]{1,5})?)$/, :message => "should be float" }
but when I enter only character in price, it accepts it and show 0.0 value for price.
can anybody tell, what is wrong in this or why this happens?
This is my solution,
validates :price,presence:true, numericality: {only_float: true}
when you fill in for example 7 it automatically transfer the value to 7.0
For rails 3:
validates :price, :format => { :with => /^\d+??(?:\.\d{0,2})?$/ },
:numericality =>{:greater_than => 0}
A float is a number and regular expressions are for strings.
It appears that when you enter a string for the float, it gets converted as 0.0 automatically by Rails.
Do you have a default (0.0) on the column? If yes, then you may try removing it and use validates_presence_of :price only.
Something to try: instead of putting the string directly into the price column, put it into a price_string attr and use a before_save callback to try to convert the string to price. Something like that:
attr_accessor :price_string
before_save :convert_price_string
protected
def convert_price_string
if price_string
begin
self.price = Kernel.Float(price_string)
rescue ArgumentError, TypeError
errors.add(ActiveRecord::Errors.default_error_messages[:not_a_number])
end
end
And in your form, change the name of the text_field to :price_string.
I'm looking for "the Rails Way" to write a validation that limits acceptable input values to a predetermined list.
In my case, I want to only accept the values "-5", "-2", "+2", "+5", and nil. However, I think this is best as a general question: how do you predefine a list of acceptable entry values in a Rails model?
Thanks!
validates_inclusion_of should work. For example:
validates_inclusion_of :attr, :in => [-5, -2, 2, 5], :allow_nil => true
You want to use validates_inclusion_of with the :in and :allow_nil options.
validates_inclusion_of :field, :in => %w(-5 -2 2 5), :allow_nil => true
You'll probably also want to use in conjunction with validates_numericality_of
Rails 3+
The modern way to do this is the following:
validates :field, inclusion: { in: [ -5, -2, 2, 5 ], allow_blank: true, message: "not an allowable number." }