Remote_form_for ajax validation


I have been reading a lot about this, but I do not manage to do a nice
validation. I already managed to save data to the database, to
validate a field, to display a “Everything went well” message. I can
also display an error message, but the view does not end up properly.

This is the form:

<% remote_form_for(product) do |f| %>
<%= f.error_messages %>

<%= f.label :title %>

<%= f.text_field :title %>

<%= f.label :body %>

<%= f.text_area :body %>

<%= f.submit “Update” %> ó

<% end %>

This is the controller:

def update
@product = Product.find(params[:id])
respond_to do |format|
if @product.update_attributes(params[:product])
flash[:notice] = ‘OK!’
format.html { redirect_to(@product) }
else[:notice] = ‘Error!!’
format.html { render :action => “show” }
format.xml { render :xml => @product.errors, :status
=> :unprocessable_entity }

The model:

class Product < ActiveRecord::Base
validates_presence_of :title

And the RJS template:

page.replace_html :description, :partial => “product”, :object =>
page.replace_html :notice, flash[:notice]
page.visual_effect (:fade, “notice”, :duration => 2)

But I thing there is a better way to validate forms.

Does any one have an example about validating, and displaying
customized messages.



Like commonly with regular forms, I prefer javascript validation
before the form submits. I happened across what I think is a valid

<% remote_form_for(product, :before => “if(!validateForm(this))
{ return false; }”) %>

Where validateForm is a javascript function that does the form
validation. Note that using this method, the javascript function MUST
return a boolean, either true for valid data, or false if not. If it’s
not valid then the form won’t submit. Within the javascript you can
put alerts or change the html with error messages so that the user can
correct their input data.