Validating Email Addresses, URLs and IP Formats with Regex in Ruby on Rails

This is all too common of faq in rails help channels and on mailing lists so it mine as well have some examples here too! Stick this in your user.rb model:

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

# AND A LOGIN VALIDATION EXAMPLE MIGHT BE

validates_format_of       :login, :with => /\w+@\w+\.\w{2}/

Format Validate for URLs

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

# OR

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

# OR

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

Format Validate Ips

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

I hope this helps you with your project and if you notice any typos or better alternatives please share.