开发者

Adding Char. Count And Limitation To Blog Entries

I am creating a Blog using RoR with a sign-in feature and I want to limit each article submission to say 1,000 characters and anyone's responding comments to 350 max. How would I implement or even start this?

Ideally the char count will count down when a char is added and change color when in the minus numbers (like Twitter).

or,

The article or comment throws up a flash notification if the user goes over the limit.

Am thinking that I can actually limit the char count adding the following in the model:

validates_length_of :article,开发者_运维知识库 :maximum => 800

validates_length_of :comment, :maximum => 400

Its the method of showing the user the remaining char count as they type, but on the client side for now? Can RoR do this?


The validations you are asking, are very simple.
I would suggest you to implement them at the client side in the browser using javascript, jquery or any other js framework of your choice.

If you do the validations at the server side, in Rails, you will still need to bind the textfield element with some javascript events associated with it.
So, don't do such validations at server-side(Rails here), if you want such a high level of UI.


You'll have to do this in javascript, since it's client side functionality that you're looking for. You should also have model validations to ensure this limit is kept (you can get around javascript validations pretty easily by just sending a POST using something like curl).

Googling for "javascript character counter" gives plenty of results.


Here's a solution that implements server-side validation and that will display a "flash" error message when validation fails.

In your Article model:

class Article < ActiveRecord::Base
  ...
  validates_length_of :note, :maximum => 1000
  ...
end

In your ArticlesController:

  def create
    @article = Article.new
    if @article.update_attributes(params)
      redirect_to articles_path
    else
      render :action => "new"
    end
  end

In your Articles view:

<%= form_for @article do |f| %>
  // This can be moved to a template
  <% if @article.errors.any? %>
  <div id="error_explanation">
    <h2>
      <%= pluralize(@article.errors.count, "error") %> prohibited this record from being saved:
    </h2>

    <ul>
      <% @article.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
  <% end %>

  // More form fields
<% end %>


Found a nice 'cross-browser' solution here via a jQuery plugin that will do the job and 'stop' users from submitting articles over the allocated amount on the client-side. Here The required Rails plugin is Here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜