Using Authlogic for general email validation 1

Posted by caike on November 05, 2009

In case you are using Authlogic for authentication in your Rails apps, then you are probably using its email format validation in the user registration step. You get this validation for free just by specifying your model to acts_as_authentic:

class User < ActiveRecord::Base

  acts_as_authentic

end

That’s it for the user model and its registration field validations (login, email and password).

But what if you have some other model in your application with an email field that you also want to validate ? You could just get your favorite email format regexp and use it with the validates_format_of method:

class Band < ActiveRecord::Base

  validates_presence_of :manager, :description
  validates_format_of :email, :with => /SomeRegexpYouGotFromGoogle/

end

But that would be decentralizing the email validation concern - totally anti-DRY and error-prone.

A better solution would be to use the email regexp that’s in Authlogic, which is the same that’s already validating your user model email field.

class Band < ActiveRecord::Base

  validates_presence_of :manager, :description
  validates_format_of :email, :with => Authlogic::Regex.email

end

That’s it. Hope it helps someone keep their code clean.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Craig Knox Wed, 02 Dec 2009 19:57:12 PST

    Awesome! Was looking for this. Keeps the code nice and DRY. Thanks!

Comments

Anti-Spam Protection by WP-SpamFree