Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one validate the format of an email field in ActiveRecord? [closed]

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?

like image 450
asmista Avatar asked Dec 09 '12 05:12

asmista


People also ask

How to validate email in Ruby?

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.

How does validate work in Rails?

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.


1 Answers

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 
like image 109
Jonathan Vukovich-Tribouharet Avatar answered Oct 11 '22 15:10

Jonathan Vukovich-Tribouharet