Ruby on Rails URL, Email, and IP Validation

Posted on May 19th, 2007 in How To, Ruby on Rails by bjones

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})?$/