Vagabond asked:

Validating forms

Tags: og nitro

How do you validate form input, and then redisplay the forms on an error with the invalid fields/errors shown?

(1 attempts)

Kashia answered:

h3. model.rb

First we add the validations to the model:

class Foo
  property :title
  
  validate_length :title, :min => 3
  validate_format :title, :format => /w/
  
  # ...
end

h3. controller.rb

Now we create an action to use that validation

class MyController < Nitro::Controller
  def action
    @errors = {}
    @values = {}
    if request.post?
      f = Foo.new
      f.title = request['title']
      if !f.valid?
        @values = {:title => request['title']}
        @errors = f.errors
        flash[:err] = "A validation error occured"
        return
      end
      f.save!
    end
  end
end

h3. action.xhtml

Now we can use the contoller action to build our validation aware form.

<!-- rest of the html code -->
<?r if err = session[:FLASH][:err] ?>
<p>#{err}</p>
<?r end ?>
<form action="/action" method="post">
  <input name="title" value="#{@values[:title]}" style="#{@errors[:title] ? 'invalid' : ''}" />
</form>
<!-- rest of the html code -->

The basic idea is, that you reuse your action.xhtml in both cases, a) you insert something the first time, and b) you were "redirected" (using the 'return' in the controller) to the form with an already filled in title which has the style invalid (style="invalid") which you can use for making a red border around it using CSS.

The "flash[:err]" is used to pass a message when rendering the next page.

I hope that helps.

Rating: 5