I want to show a error message to the user if his comment is too short

by Felipe Lisboa   Last Updated July 11, 2019 19:26 PM

I'm doing a feature to my boss website, that is, if a person writes down a comments that has less than 5 words I would show him a error message saying, "1 error prohibited your comment from being saved" *comment is too short (minimum 5 characthers).

I do not have much experience with rails nor ruby, but my boss asked me to do that so...





Answers 1


Add this into your model (comment.rb?):
validates :text, length: { minimum: 5 } (change :text to name of field that should be validated)

Download https://github.com/ryanb/nifty-generators/blob/master/lib/generators/nifty/layout/templates/error_messages_helper.rb or https://github.com/ryanb/nifty-generators/blob/master/lib/generators/nifty/layout/templates/error_messages_helper.rb into your project (into app/helpers directory).

Add <%= f.error_messages %> into your template (below <%= form_for ... do |f| %>)

More information about validation:
https://guides.rubyonrails.org/active_record_validations.html#length

http://railscasts.com/episodes/211-validations-in-rails-3?view=asciicast

sigmaray
sigmaray
July 11, 2019 19:25 PM

Related Questions



Rails Background Jobs running twice

Updated December 06, 2017 01:26 AM


render another controller action and filling form

Updated November 11, 2017 20:26 PM

Bootstrap Modal Plugin is not working properly

Updated December 03, 2018 20:26 PM