I'm using Rails 4.0 with Ruby 1.9.3. I have two REGEXs for validating two different fields:
PRICE_REGEX = /[0-9]+/
VALID_REGEX = /[a-zA-z0-9]*/
validates :price, presence: true, format: { with: PRICE_REGEX }
validates :title, length: { maximum: 20 }, format: { with: VALID_REGEX } #not a required field.
In my form, I'm using the form_for and have these fields represented as:
<li>
<div class="msglabel">Price:</div>
<%= f.text_field :price, class:"textArea" %>
</li>
<li>
<div class="msglabel">Title:</div>
<%= f.text_field :title, class:"textArea" %>
</li>
Unfortunately, neither of these are working. I can enter any ASCII character in either field and they will accept them. The VALID_REGEX works when I use
VALID_REGEX = /[a-zA-z0-9]+/
but then it won't accept an empty field, which I need it to because it isn't required.
What am I doing wrong and how can I rectify it?
EDIT
I've added the \A and \z anchors to the regex:
PRICE_REGEX = /\A[0-9]+\z/
VALID_REGEX = /\A[a-zA-Z0-9]*\z/
So VALID_REGEX is working but PRICE_REGEX won't even accept proper inputs now, such as 5000. I've tested it via Rubular, where it works perfectly, but my application just won't accept any input at all.