[ rails ] activeRecord validation

validates_presence_of :email
validates_length_of :email, :maximum => 50
validates_uniqueness_of :email
validates_format_of :email, :with => EMAIL_REGEX
validates_confirmation_of :email

short form

validates :email :presence => true
                 :length => {:maximum => 50 },
                 :uniqueness => true,
                 :format => {:with => EMAIL_REGEX},
                 :confirmation => true

other uses

:numericality => boolean
:inclusion => {:in => array_or_range}
:exclusion => {:in => array_or_range}
:acceptance => boolean


Test on rails console

record.valid?
record.errors.full_messages
record.errors.clear  # if we call valid? also clear the errors


Custom Validation

FORBIDDEN_USERNAMES = ["test", "test"]
validate :custom_method, :on => :create

def custom_method
	if FORBIDDEN_USERNAMES.include?(username)
	    errors[:base] << "test add to base"
		errors.add(:username, "has been restricted from use")
	end
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s