Starting Small
The most likely place that youâre going to use regular expressions
in Rails is the validates_format_of
method demonstrated
in Chapter 7, which is
shown here as Example C-1.
Example C-1. Validating data against regular expressions
# ensure secret contains at least one number validates_format_of :secret,:with => /[0-9]/
, :message => "must contain at least one number" # ensure secret contains at least one upper case validates_format_of :secret,:with => /[A-Z]/
, :message => "must contain at least one upper case character" # ensure secret contains at least one lower case validates_format_of :secret,:with => /[a-z]/
, :message => "must contain at least one lower case character"
These samples all use regular expressions in their simplest
typical use case: testing to see whether a string contains a pattern.
Each of these will test :secret
against the expression specified by :with
. If the pattern in :with
matches, then validation passes. If not,
then validation fails and the :message
will be returned. Removing the Rails
trim, the first of these could be stated roughly in Ruby as:
if :secret =~
/[0-9]/
#yes, it's there
else
#no, it's not
end
The =~
is Rubyâs way of
declaring that the test is going to compare the contents of the left
operand against the regular expression on the right side. It doesnât
actually return true
or false
, thoughâit returns the numeric position
at which the first match begins, if there is a match, and nil
if there are none. You can treat it ...
Get Learning Rails now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.