Sep302009
Active Record Validator (DRY Approach)
Comments Off
With the release of Rails 2.3.4, It includes validators independent from models. Rails is going much more DRY.
For this one just have to define a class that inherits ActiveRecord::Validator and there you go
Let’s see an example:
1 2 3 4 5 6 | class EmailValidator < ActiveRecord::Validator def validate record.errors[:email] << “is not valid” unless record.email =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i end end |
Validate method override validate method of parent class. Now you can include this to any of your model.
Let’s see HOW?
1 2 3 | class bussiness < ActiveRecord::Base validates_with: EmailValidator #That’s all end |