I need a way to only allow values like:
Ok: 23.55, 232.43, 300.34 2.34
Not ok: 23.4, 43.344, 343.454, 230, 34
I have a regex in my model but it seems to allow me to save values like 200, 344, 23
. I need to restrict things so that I'm only allowed to submit form when values are entered in the format of my Ok list.
Here is my model:
class Garment
include ActiveAttr::Model
#include ActiveModel::Validations
extend CarrierWave::Mount
attribute :price
mount_uploader :image, ImageUploader
price_regex = /\A(?:[1-9]+[0-9]*|0)(?:\.[0-9]{2})?\z/
validates :price, :presence => true,
:numericality => { :less_than => 301.00, :greater_than => 0.00 },
:format => {
:with => price_regex,
:message => "Price must be entered in the correct format e.g. 23.45, 203.43 not 43.3 or 234.5"
}
This is how I save the price entered into the form field:
def create
@garment = Garment.new(params[:garment])
if @garment.valid?
garment = Parse::Object.new("Garments")
garment["price"] = params[:garment][:price].to_f
garment.save
flash[:success] = "Garment successfully added to store!"
redirect_to '/adminpanel/show'
else
render "new"
end
end
I thought my regex was fine but I think I may need to tweak it more. I was wondering maybe I could some how check the value for a decimal and if it hasn't got one add one with 2 zeros after it before it is saved.
However I think the easiest most sensible way would be to do something before the actual form is submitted.
Would appreciate some help
Thanks for your help