Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

ruby on rails - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

^ 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
zzzz"
# => "abcde
zzzz"

/^abcde$/ === string
# => true

/Aabcdez/ === 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...