# Custom Validation

**URL:** <https://www.ruby-forum.com/t/custom-validation/114915>\
**Category:** Rails\
**Created:** [September 18, 2007, 7:45pm UTC](https://www.ruby-forum.com/t/custom-validation/114915 "2007-09-18T19:45:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mslagell](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e274bd/32.png) [@mslagell](https://www.ruby-forum.com/u/mslagell)\
**Post date:** [September 18, 2007, 7:45pm UTC](https://www.ruby-forum.com/t/custom-validation/114915/1 "2007-09-18T19:45:20Z")

</div>

Hello all,

I’m trying to figure out how to validate a zip code in my user model.  
I can validate it’s all nuneric and five digits but I would like to  
validate it against a zip code table.

I know I need to create a zipcodes table and assume a zipcodes model.  
In the user model, how/where do I call the Zipcode.find ?

Thanks

---

<div class="post-metadata">

**Author:** ![mslagell](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e274bd/32.png) [@mslagell](https://www.ruby-forum.com/u/mslagell)\
**Post date:** [September 18, 2007, 8:14pm UTC](https://www.ruby-forum.com/t/custom-validation/114915/2 "2007-09-18T20:14:28Z")

</div>

Hi Mark,

I’m assuming you want to validate the zipcode when saving (say) an  
address.  
So in your address model, put something like this:

validates\_each :zipcode do |model, attr, value|  
model.errors.add(attr, “is not valid”) if Zipcode.find\_by\_zipcode  
(value).nil?  
end

Where Zipcode is the name of your zipcode model that contains valid  
zipcodes. This assumes that zipcodes in the zipcode table are unique.  
I  
don’t think I’ve ever used the word zipcode this many times in a single  
email.

-Dan
