When I tried to check the validation of the model with a regular expression in Rails, an error occurred, so make a note as a memorandum.
Ruby 2.5.1
Rails 5.2
user.rb
class User < ApplicationRecord
validates :age, format: { with: /^[0-9]+$/, message: "Can only be entered as a number."}
end
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?
As for the content of the error, it seems that it is said that \ A
, \ z
can be used because ^
, $
has a security risk.
^
→ A
$
→ z
If it is not the above method, you can add the : multiline => true
option to prevent the error from occurring even in the code containing the vulnerability.
According to my research, regular expressions have become stricter as a security measure since Rails 4.
In Ruby, if you want to make a match with a specific head and end, it seems better to implement it as follows.
There is a way to add the : multiline => true
option, but in the case of validation processing etc., I felt that it is better not to specify it unless there is a special reason.
user.rb
class User < ApplicationRecord
validates :age, format: { with: /\A[0-9]+\z/, message: "Can only be entered as a number."}
end
For the time being, it is defined as follows in the official Ruby reference.
^ Matches the beginning of a line. The beginning of a line means the beginning of a character string or after a line break. $ Matches the end of a line. The end of a line means the end of a character string or before a line break. \ A Matches the beginning of a string. \ z Matches the end of the string.
Use \ A and \ z instead of ^ and $ for regular expression validation Regular expressions have become stricter in Rails 4. Ruby 2.7.0 Reference Manual Regular Expression
Recommended Posts