# Custom validation methods

**URL:** <https://www.ruby-forum.com/t/custom-validation-methods/122790>\
**Category:** Rails\
**Created:** [December 12, 2007, 6:32am UTC](https://www.ruby-forum.com/t/custom-validation-methods/122790 "2007-12-12T06:32:25Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![S-gw](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ed655f/32.png) [@S-gw](https://www.ruby-forum.com/u/S-gw)\
**Post date:** [December 12, 2007, 6:32am UTC](https://www.ruby-forum.com/t/custom-validation-methods/122790/1 "2007-12-12T06:32:25Z")

</div>

I’ve been working on extending AR validations with some custom  
methods with the goals to:

a) reduce the bulk the standard syntax can result in  
b) avoid having to write and read regex for common white-listed  
character sets  
c) allow some UTF-8 characters  
d) provide a mechanism for making dynamic error messages

I’ve written a detailed article how I did it, and I’ve posted the  
source I generated to be used or just looked at as an example. Thanks  
to everyone that answered the questions that got me to this point.

[http://www.railsdev.ws/blog/11/custom-validations-in-rails/](http://www.railsdev.ws/blog/11/custom-validations-in-rails/)

I reduced this application code (which does not allow for UTF-8 chars):

validates\_format\_of  
:userFltrName,  
:with =\> /^[a-zA-Z0-9\_-\]\*?$/,  
:message =\> ‘accepts only letters, 0-9, underscore, hyphen, and  
space’

validates\_format\_of  
:userFltrTable,  
:with =\> /^[a-zA-Z0-9\_]\*?$/,  
:message =\> ‘accepts only letters, 0-9, and underscore’

validates\_format\_of  
:userFltrField,  
:with =\> /^[a-zA-Z0-9\_]\*?$/,  
:message =\> ‘accepts only letters, 0-9, and underscore’

validates\_inclusion\_of  
:userFltrOp,  
:in =\> %w{eq bw ew cn lte lt gte gt btw},  
:message =\> ‘has a value other than the valid options below’

down to the following replacement (which does allow UTF-8 chars):

validates\_as\_alpha\_numeric\_separator :userFltrName  
validates\_as\_alpha\_numeric\_underscore :userFltrTable, :userFltrField  
validates\_as\_value\_list :userFltrOp, :in =\> %w{eq bw  
ew cn lte lt gte gt btw}

So far, I have validators for:

validates\_as\_person\_name  
validates\_as\_business\_name  
validates\_as\_street\_address  
validates\_as\_alpha  
validates\_as\_alpha\_space  
validates\_as\_alpha\_hyphen  
validates\_as\_alpha\_underscore  
validates\_as\_alpha\_symbol  
validates\_as\_alpha\_separator  
validates\_as\_alpha\_numeric  
validates\_as\_alpha\_numeric\_space  
validates\_as\_alpha\_numeric\_hyphen  
validates\_as\_alpha\_numeric\_underscore  
validates\_as\_alpha\_numeric\_symbol  
validates\_as\_alpha\_numeric\_separator  
validates\_as\_numeric  
validates\_as\_decimal  
validates\_as\_positive\_decimal  
validates\_as\_integer  
validates\_as\_positive\_integer  
validates\_as\_email  
validates\_as\_value\_list

–  
def gw  
acts\_as\_n00b  
writes\_at(www.railsdev.ws)  
end
