Forum: Ruby on Rails how to validate form ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jamal S. (Guest)
on 2007-02-16 02:56
Hello there,

Rails is funny, I had been using PHP since 2001, and I learned many
other programmer language, but rails is hard to find around, the manual
is messy, you cannot get any good description from it as shown below!

validate(
Overwrite this method for validation checks on all saves and use
Errors.add(field, msg) for invalid attributes.

This above doesn't help me anyway to know how to use this method :S:S:S:
and then I tried to find anything on google search results, and ended
with...

if params[:user][:username].blank?
  @errors << " missing"
end

*This again does aren't working :(...

Can anyone help me out there to know how to get started, things are more
complicated then I thought, I don't think you would like me to create
new topic every time I face a problem and use 1 hour on it.

//Jamal
Mike G. (Guest)
on 2007-02-16 03:03
(Received via mailing list)
your validations should go into your model class, not in your
controller.  So to ensure that your user object has a username
associated with it, put the following in your user.rb class:

validates_presence_of :username

and then an error will occur when you attempt to save a User object
from your controller, using something like the following:

@user = User.new(params[:user])

if @user.save
   #save was successful
else
   #save was unsuccessful, the error will be stored in the @user object
end

you can then display the errors associated with an object by putting
the following in your view code:

<%= error_messages_for :user %>

if you find that the built in validations don't do what you want, you
can always override the validate method in your model, such as the
following:

user.rb

def validate
   errors.add(:username, "must not be john") if username == "john"
end

Mike
This topic is locked and can not be replied to.