Sunday, December 16, 2007

Common rails validations



A rather short post, this one if focused on few validations in rails that I often use. In rails you could do a lot of validations, as they are very simple to handle. Because of the well structured and separated MVC architecture all you need to do is write you validations for the database in our model. Actually as a matter of fact you could also write them as a library and call its methods. The ones below aim to do just that. They use regular expressions, in case you are confused with what that is do read up.

Validating an Email Address

validates_format_of(:email,
:with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i,
:on => :create,
:message=>"has an invalid format")

Validating URLs

validates_format_of :url, :with => /^(https?://)?([^/]+)(/.+)?$/i

# OR

validates_format_of :url, :with => /^(ftp|https?)://((?:[-a-z0-9]+.)+[a-z]{2,})/

Validating IP addresses

validates_format_of :ip, :with => /^(d{1,3}.d{1,3}.d{1,3}.d{1,3})?$/

=================================================
||My FREE services||

ParkingWHOIS is now not only a domain parking lookup, but now also has reviews on Parking Companies.
=================================================


No comments: