# Problem requiring custom validation

**URL:** <https://www.ruby-forum.com/t/problem-requiring-custom-validation/108965>\
**Category:** Rails\
**Created:** [July 10, 2007, 2:00am UTC](https://www.ruby-forum.com/t/problem-requiring-custom-validation/108965 "2007-07-10T02:00:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Cynthia\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/db5fbb/32.png) [@Cynthia\_K](https://www.ruby-forum.com/u/Cynthia_K)\
**Post date:** [July 10, 2007, 2:00am UTC](https://www.ruby-forum.com/t/problem-requiring-custom-validation/108965/1 "2007-07-10T02:00:12Z")

</div>

I have occasion to validate email addresses in multiple models over  
projects, so I decided to start a custom validation library. Google  
led me to this write up that is essentially what I want - but with a  
different format - [http://www.yoman.com.sg/ruby-and-rails](http://www.yoman.com.sg/ruby-and-rails)

# lib/custom\_validators.rb

module ActiveRecord::Validations::ClassMethods

def validates\_as\_email(\*attr\_names)  
configuration = { :message =\> “is not a valid email address”, :on  
=\> :save, :allow\_nil =\> true }  
configuration.update(attr\_names.pop) if attr\_names.last.is\_a?(Hash)

```
validates_each(attr_names,configuration) do |record, attr_name, 

```

value|  
record.errors.add(attr\_name, configuration[:message]) unless  
value.to\_s =~ /(^([^@\s]+)@((?:[-\_a-z0-9]+.)+[a-z]{2,})$)|(^$)/i  
end  
end

end

# config/environment.rb

require ‘custom\_validators’

# app/models/user.rb

class User \< ActiveRecord::Base  
validates\_as\_email :email  
…

But I had trouble getting my new validation recognized so I could use  
it in the same way I use the built in validations. My rails instance  
(version 1.2.3) seems to be ignoring my ‘require “custom\_validators”’  
call in environment.rb. The only way I could get around the  
NoMethodErrors was to place ‘require “custom\_validators”’ at the top  
of the model class where I wanted to use it (e.g. app/models/user.rb).  
This isn’t killer - but it does mean that I can’t seamlessly extend  
the Rails core by just hooking things in once.

1. Have things changed since the tutorial I referenced was written? I  
found Peter M.'s article a little less clear to me  
([Peter Marklund's Home](http://www.marklunds.com/articles/one/312)), but it seems to still  
imply that placing the custom validations in a file in lib should  
cause them to be loaded automatically or perhaps semi-automatically.

2. Is there a way to do what I want? Extend Rails with my custom  
validations and only have to hook it in once (not in every model where  
I want to use them).

–  
Cynthia K.  
removed\_email\_address@domain.invalid
