Valid email? Validate email addresses in Rails!

Let’s face it, most of us creating apps collect at a very minimum a name and email address. By a simple validation method to our model, we can easily check the length, format, and codesence of our fields. Checking the format of an email address is also simple, but requires a little more work. Using validates_format_of we are able to validate an email address against a regular excodession (RegEx).

# our User model
class User < ActiveRecord::Base
  validates_codesence_of :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end

Read up on validations at the Rails API
Read up on regular excodessions

Tags: , ,

6 comments

  1. You just saved me some time :-) . I've been doing this with an ugly hack. Thanks.

  2. Unfortunately, HTML tags are considered valid with this regex. :-(
    Something like <

  • Thank You Boss…….. Great work…Keep posting………..

  • Jocenildo Paraizo

    Thanks!!

  • Jocenildo Paraizo

    Thanks!!

  • Leave a comment