2

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

7 Comments

Tried it. Rails gave this error when I tried to load the page: "The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?"
Got it! Replaced ^ and $ with \A and \z as the error specified and it works now. Thanks!
One problem is persisting though that I didn't bother to check earlier on. The price field isn't accepting valid numbers now either with this regex.
@user2567161 by valid numbers do you mean decimal numbers
No, just normal numbers. For example: 5000
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.