Question

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.

Was it helpful?

Solution

I guess you are missing \A(beginning of string),\z(end of string)

PRICE_REGEX = /\A[0-9]+\z/
VALID_REGEX = /\A[a-zA-Z0-9]*\z/

Without \A,\z it could match anywhere in middle like in the case of Hello! Hi which would match..With \A,\z you would explicitly match from start till end of string without matching anywhere in between


Refer to anchors in docs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top