Ruby on Rails: Validation in Models
It is natural that when you are going to accept a new thing, you have a different kind of feeling. The same thing applied to me when I was first introduced to Ruby on Rails to accept as a new web language and framework that was based on MVC. It’s a big challenge to learn a whole new language and a new well-structured framework.
It’s been for some time now that I am using RoR and I must point out here that it is a very good learning experience.
Here I want to share my some programming experience with you all. It’s related to validations in Models:
What Is This? And where it belongs?
Validation belongs in the domain model.
Ruby on Rails has convinced me that putting the validation in the domain model is generally the best approach. Model class can be a perfect place to keep all your data validations
Now With Rails using Active Record, a few ideas generate in our mind as how its done, when the object fails to validate those validation errors, what’ll be returned in the web form, web service etc...
The validation just happens by default.
There are some more situations like if one gets the validation right then he doesn’t need to worry about another programmer to write a web service to manipulate data.
In Rails, to check that data is according to the requirement is important and easy.
Usages of Validations:
Basically we could write validations in 3 passes,
Pass 1: Use Rails inbuilt simple validation rules
a) Field should not be empty
Rails Method: validates_presence_of
Example: validates_presence_of :user_name,: password
b) Field should Numerical
b) Rails Method: validates_numericality_of
Example: validates_numericality_of :price
c) Field should not be Unique
Rails Method:validates_uniqueness_of
Example: validates_uniqueness_of :username
d) Field Need to be of size X
Rails Method: validates_length_of
Example: validates_length_of: zipcode, :is=>5
e) Field size Need to be of between X to Y
Rails Method: validates_length_of
Example: validates_length_of :password, :in => 6..40, :on => :save
Pass 2: Write Regular Expression to do validation
Requirement: Field Need to be in Certain Format like Email or DOB
Rails Method: validates_format_of
Example: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
(you could add :message => “This email should be in proper format” to customize Error Messages)
Pass 3 : Custom Validations
Finally, for any other custom validations like say if product price should be more than $50 define a protected method “validate” inside your model. Then use errors object to add any messages if validation fails like errors.add (:your_field, “your message”).
def validate
errors.add(:price, “should be a positive value”) if price.nil?|| price < 0.01
end
One Example to include these three above passes:
class Contact < ActiveRecord::Base
validates_presence_of :firstname, :if => Proc.new {|d| d.firstname }
validates_numericality_of :phone, :only_integer => false , :if => Proc.new {|p| p.phone != ''}
def validate
if email == ''
errors.add(:email, "can't be blank")
end
if phone != ''
errors.add(:phone, "should be a positive value") if phone == 0 || phone.to_f < 0.01
end
if phone != ''
errors.add(:phone, "should be a integer value") if phone.include? "."
end
if length!=nil || breadth!=nil || height!=nil
errors.add(:length, ", breadth and height should not be blank") if length==nil || breadth == nil || height ==nil
end
unless self.zip.to_s.size == 5
errors.add (:zip, "should be 5 digits") if zip!=nil and zip > 0.01
end
end
validates_length_of :phone, :within=>10..12 , :if => Proc.new {|p| p.phone != '' and p.phone.to_f >0.01}
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :save, :if => Proc.new {|c| c.email and c.email != '' }
validates_uniqueness_of :email, :scope => [:id], :on => :save,:if => Proc.new {|c| c.email and c.email != '' }
end
- ruchi's blog
- Login to post comments


