Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
# Chuck this in config/initializers for view-first validations
ActionView::Base.default_form_builder.class_eval do
def error(field)
errors(field).first
end
def errors(field)
object.errors.for(field)
end
end
ActiveRecord::Errors.class_eval do
def generate_message(attribute, message = :invalid, options = {})
message
end
def for(attribute)
case err = self.on(attribute)
when String, Symbol: [err]
when Array: err
when NilClass: []
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 :invalid
.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?")
- when :foo
.error.foo= _("You need to foo first")
class User < ActiveRecord::Base
validates_presence_of :email, :name, :password,
validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, :allow_blank => true
validates_uniqueness_of :email, :case_sensitive => false
my_custom_validates_of :email, :message => :foo
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.