Friday, May 20, 2005

Rails model validation

The more I look at rails, the more impressed I become. I've done validation on various web platforms, and nothing is as straightforward and sensible as the way Rails handles it. I had liked ASP.NET's validator controls, but that was before I experienced the sweet simplicity of the Rails ActiveRecord validation methods. The problem with ASP.NET, and most other frameworks, is that you have to duplicate validation in the view (ui controls, javascript) and the model (business objects). With Rails, in the spirit of DRY, it is coded in the one place it should be, the model.

class Category < ActiveRecord::Base
validates_length_of :category,
:within => 1..20
validates_uniqueness_of :category,
:message => "already exists"
validates_format_of :category,
:with => /^[^<>]+$/,
:message => "no brackets!"
validates_format_of :category,
:with => /^[^(fudge|shucks|gosh darn)]+$/i,
:message => "no cursing!"


Post a Comment

Links to this post:

Create a Link

<< Home