Marky Chor
Marky Chor

Reputation: 1

Rails Application Form Validation

I'm working on a Rails project, and I want to implement form validation on it. When client side and/or server side validation fails, I want to autopopulate the form fields with the values entered by the user earlier and pointing those fields which were incorrect.

What I'm trying to implement is creating a Model ValidForm and using validates for client side validation. How should I proceed with auto-populating form fields and keeping track of what caused form validation fail. Also in this form I have to upload a file which needs to be checked for validation on server side.

I'm a beginner in Rails, so please point me in the right direction to implement this.

Upvotes: 0

Views: 1184

Answers (1)

Zoran
Zoran

Reputation: 4226

Below is a very general example for creating a form which would display validation errors, while retaining input values. In this example, assume that we have a Post model already set up:

app/controllers/posts_controller.rb:

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      flash[:success] = "Post was created!"
      redirect_to posts_path
    else
      flash[:error] = "Post could not be saved!"
      # The 'new' template is rendered below, and the fields should
      # be pre-filled with what the user already had before
      # validation failed, since the @post object is populated via form params
      render :new
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :body)
  end
end

app/views/posts/new.html.erb:

<!-- Lists post errors on template render, if errors exist -->

<% if @post.errors.any? %>
  <h3><%= flash[:error] %></h3>
  <ul>
  <% @post.errors.full_messages.each do |message| %>
    <li>
      <%= message %>
    </li>
  <% end %>
<% end %>

<%= form_for @post, html: {multipart: true} |f| %>
  <%= f.label :title %>
  <%= f.text_field :title, placeholder: "Title goes here" %>

  <%= f.label :body %>
  <%= f.text_area :body, placeholder: "Some text goes here" %>

  <%= f.submit "Save" %>
<% end %>

The above is a basic setup that would display to a user what fields failed validation, while keeping the input field values when the template is rendered. There are tons of libraries out there for forms which can help make your forms look/behave better - here are two popular options:

There is also a useful RailsCasts screencast on client side validations.

The RailsGuides has a great set of docs on ActiveRecord (model) validation.

Hope this helps!

Upvotes: 1

Related Questions