Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions with validations in RoR 4

There is the following code:

class Product < ActiveRecord::Base   validates :title, :description, :image_url, presence: true   validates :price, numericality: {greater_than_or_equal_to: 0.01}   validates :title, uniqueness: true   validates :image_url, allow_blank: true, format: {       with: %r{\.(gif|jpg|png)$}i,       message: 'URL must point to GIT/JPG/PNG pictures'   } end 

It works, but when I try to test it using "rake test" I'll catch this message:

rake aborted! 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? 

What does it mean? How can I fix it?

like image 720
malcoauri Avatar asked Jul 20 '13 07:07

malcoauri


People also ask

How do you validate a regular expression?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything. So there's no need to write your own RegExp validator.

How do you make a regular expression in Ruby?

* ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash. Following table lists the regular expression syntax that is available in Ruby.

How do you match a string in Ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.


1 Answers

^ and $ are Start of Line and End of Line anchors. While \A and \z are Permanent Start of String and End of String anchors.
See the difference:

string = "abcde\nzzzz" # => "abcde\nzzzz"  /^abcde$/ === string # => true  /\Aabcde\z/ === string # => false 

So Rails is telling you, "Are you sure you want to use ^ and $? Don't you want to use \A and \z instead?"

There is more on the rails security concern that generates this warning here.

like image 169
oldergod Avatar answered Sep 23 '22 01:09

oldergod