This is a continuation of the previous article .
After setting validation in the name and email columns, I'd like to use a regular expression to determine if it's a valid email address ([email protected], etc.), but Ruby reference , you may be drowning in a huge amount of information. .. .. So, this time, I decided to investigate and use only what is necessary to determine whether email is valid.
From the conclusion, here is the regular expression used this time.
/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
Regarding regular expressions, Rails tutorial is explained more clearly than the Ruby reference. It was. The following is an excerpt from the Rails tutorial, but it seems that you can understand it while looking at this.
Regular expressions | meaning |
---|---|
/\A[\w+-.]+@[a-z\d-.]+.[a-z]+\z/i | (Complete regular expression) |
/ | Indicates the start of a regular expression |
\A | The beginning of the string |
[\w+-.]+ | Alphanumeric, underscore(_),plus(+),hyphen(-),Dot(.)Repeat at least one character |
@ | At sign |
[a-z\d-.]+ | Repeat at least one letter of lowercase letters, numbers, hyphens, or dots |
. | Dot |
[a-z]+ | Repeat at least one lowercase letter |
\z | End of string |
/ | Indicates the end of a regular expression |
i | Ignore case option |
You can also use Rubular to easily check regular expressions. This is convenient!
Then, add this regular expression to the validation created in previous article . To verify the format. .. ..
validates :email, format: { with: /<regular expression>/ }
Since it is said that the format option is used in this way, add a regular expression in the place of "regular expression". app/models/user.rb
class User < ApplicationRecord
validates :name, presence: true, length: { maximum: 20 }
validates :email, presence: true, length: { maximum: 300 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
end
When I tried to register by typing email: "ruby" in the Rails console, I got an error because it didn't look like [email protected]. It's very convenient if you can master regular expressions!
> user = User.create(name: "ruby", email: "ruby")
(0.2ms) BEGIN
(0.3ms) ROLLBACK
=> #<User id: nil, name: "ruby", email: "ruby", created_at: nil, updated_at: nil>
> user.errors.messages
=> {:email=>["is invalid"]}
Recommended Posts