Reputation: 570
We can validate email by doing:
validates :email, format: { with: VALID_EMAIL_REGEX }
or
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
What is the difference between the 2 approaches. Is one approach better than the other?
Upvotes: 3
Views: 1544
Reputation: 11570
There is no difference between those two forms. The first is just a convenient shortcut for being able to specify multiple validations on a single attribute. For example, let's say you wanted to ensure that an email is valid but also unique. Using the second form in your example, this would be written
validates_uniqueness_of :email
validates_format_of :email, with: VALID_EMAIL_REGEX
Or, it could be written more succinctly using validates
validates :email, uniqueness: true, format: { with: VALID_EMAIL_REGEX }
What's also nice about using validates
is that you can mix default validations with your own custom validations with a single call to validates
. More information here.
Upvotes: 6