I have a User model in a Rails application which has an email field. Is there a default validation that will ensure the email is in the correct format? If not, how would I go about validating that field?
The first validation method, validates_presence_of, checks whether the email field is empty. The second method, validates_format_of, compares the email with the particular regular expression. The advantage here is that the same regular expression can be used to validate emails in different classes and methods.
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
Add in your gemfile:
gem 'validates_email_format_of'
and in your model:
validates :email, email_format: { message: "doesn't look like an email address" }
Or if you don't want use a gem, use regex:
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With