Auto checking forms
Posted by Sandro Paganotti in
Ruby on Rails -
comments are closed
First of all we need to structure our form in order to specify for each field if it is required or not; to do this we can use the already tested and implemented hash-like params structure simply by adding another level of depth:
required fields must be putted under [obb] level
<%= text_field_tag "form_fields[obb][name]", get_from_params(params[:form_fields],:obb,:name) %>
optional fields must be putted under [fac] level
<%= text_field_tag "form_fields[fac][name]", get_from_params(params[:form_fields],:fac,:name) %>
The 'get_from_params' helper function does exactly the same as 'params[:form_fields][:fac][:name]' plus it checks that params[:form_fields][:fac] is not blank, preventig in this way the thrown of an exception.
def get_from_params(param,stato,nome)
return param[stato][nome] unless param.blank? or param[stato].blank?
return nil
end
Now we just need to check in our controller if the fields under the [obb] section are filled:
# put this inside the controller at which the forms refer
errors = []
if params[:form_fields][:obb].blank?
flash[:notice] = "All the required fields are missing".t
# ERROR - none of the required fields has been filled
return
end
params[:form_fields][:obb].each_pair do |key,value|
errors << "field #{key} is required".t if params[:form_fields][:obb][key.to_sym].blank?
end
if errors.length > 0
flash[:notice] = errors.join(" and ").capitalize
# ERROR - some required fields are missing
return
end
# NOERROR - Everithing went fine
What's missing here is a way to ensure that the user cannot alter your required fields list by using a tool such firebug; a solution could be adding an hidden field in each form containing a digest (ie: MD5) created by using a secret word plus all of the names of the required fields of that form (eg "mysecretw" + "name" + "email").


Comments
Dante Regis
Posted on November 18