I have got a form which accepts a “paid” field and I am attempting to validate it.
It’s a numeric field but I want the user to be able to enter the paid amount without comma raising error by checking validation.
amol.rb
class Amol < ApplicationRecord
validate :check_paid
def check_paid
errors.add(:paid, '- Commas are not allowed') if paid.to_s.gsub(/,/,"").to_i
end
end
When I enter the paid amount as 12,535 then it raises the error displaying as below ;
1 error prohibited this article from being saved: Paid - Commas are not allowed
and that is okay.
But the problem is even if I remove comma from the input, still the error persists and I cannot create or update the form.
Any suggestions are most welcome.
Thank you in advance.
Finally, I got the desired result by using the validation as below;
validates :paid, numericality: { only_integer: true }, allow_nil: true
Now when I enter comma in the text field, I get the error displaying ;
Paid is not a number
On the other hand, If entered the number without comma and saves to the database as expected.