Reputation: 9085
I am using Rails 3.2.13
and ruby 1.9.3p194
I have added client side validation to allow user to enter only numbers[0-9] and decimal[.] in price field. My code is as follows:
price.js.coffee
$("input").bind "keypress", (event) ->
regex = new RegExp("^[1-9]\d*(\.\d+)?$")
key = String.fromCharCode((if not event.charCode then event.which else event.charCode))
unless regex.test(key)
false
form.html.haml
= simple_form_for :purchase, url: purchase_path, method: :post do |f|
= f.input :value, as: :integer, label: 'Amount',
input_html: { min: "0.01", value: number_with_precision(precision: 2)}
Currently I am able to enter numbers in the textbox but I am unable to add a decimal point. I dont know where I am making a mistake. Any help is much appreciated.Thnx:)
Upvotes: 0
Views: 381
Reputation: 21
I think the problem lies with your regex.
Try:
/^[0-9]\d*\.\d{2}$/
This will only allow prices ending in 2 digits after a decimal place e.g:
12.99, 13.00, 1.50, 0.30
but not
12.1, .05, 15.999, 13
Hope that helps!
Upvotes: 1