Skip to content

Instantly share code, notes, and snippets.

@toolmantim
Created May 6, 2009 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save toolmantim/107555 to your computer and use it in GitHub Desktop.
Save toolmantim/107555 to your computer and use it in GitHub Desktop.
# Chuck this in config/initializers for view-first validations
ActionView::Base.default_form_builder.class_eval do
def error(field)
case err = object.errors.on(field)
when String: err
when Array: err.first
end
end
def errors(field)
case err = object.errors.on(field)
when String: [err]
when Array: err
when Nil: []
end
end
end
-# And you can use it in a view like so:
- form_for :user, @user, register_path do |f|
%fieldset
!= f.label :name
!= f.text_field :name
- if f.error(:name) == "blank"
.error.name_blank You don't have a name??
!= f.label :email
!= f.text_field :email
- case f.error(:email)
- when "blank"
.error.email_blank You don't have an email??
- when "format"
.error.email_format That doesn't look like an email address!
- when "taken"
.error.email_taken
There is an account already registered with that email address.
%a{:href => root_path(:email => @user.email)} Log in instead?
class User < ActiveRecord::Base
validates_presence_of :email, :name, :password, :message => "blank"
validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, :allow_blank => true, :message => "format"
validates_uniqueness_of :email, :case_sensitive => false, :message => "taken"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment