Client side validation with judge not working - ruby-on-rails

I am trying to use client side validation with Judge gem but validation not working.
In my gem file I used
# Forms
gem 'simple_form', '3.0.2'
#Client side validations
gem 'judge'
I have simlpe_form gem and I know i need to use plugin for simple form with judge but i am trying to use in normal form_for but its not working with that either.
My model looks like
class User < ActiveRecord::Base
paginates_per 10
validates :name , presence: true, length: { maximum: 200 }
In my view
- title 'User Registration'
.vcentered
.signup-box
- if #user.authorizations.any?
%h1 We just need a little more information...
- else
%h1 We just need a little bit of information...
= form_for #user,:builder => Judge::FormBuilder, url: user_registration_path, html: { class: 'new-user form-default' } do |f|
- if #user.name.blank?
= f.text_field :name, class: class_with_errors(#user, :name),
title: title_with_errors(#user, :name),
placeholder: 'Full Name',
:validate => true
I have followed all configuration stps as given on github page of gem.
Please suggest solution of the problem or how I can find the cause of problem.
in client side validation when i load the page browser is saying (at top middle, I forget what it is called)
The page at localhost: 3000 says: PAge can't be blank. Any idea why it is working like this ?

rails generate judge:install path/to/your/js/dir
and then in your route.rb
mount Judge::Engine => '/judge'

Related

form_with client side validation

Im using the client side validation gem. And have ran the all the instructions as stated to get validation working, but validation doesnot work on my form.
My form:
<%= form_with(model: profile, local: true, method: :patch, multipart: true, validate: true) do |form| %>
I have put validate: true as stated on document.
Rather than put validation in my model:
validates :name, :email, presence: true, length: { maximum: 10 }, if: :can_validate?
def can_validate
true
end
The doc says you can force on the form which I have done instead:
And in my text field I have applied the validation:
<%= form.text_field :name, validate: { presence: true }, id: :profile_name, class:"input is-large" %>
But the validation does not work at all, no error message.
I created a repo to reproduce your issue myself:
https://github.com/wmavis/so_rails_client_side_validations
It looks like client_side_validations works for me if I use form_for but does not work for me if I use form_with:
A search for "client_side_validations form_with" turned up this link:
https://github.com/DavyJonesLocker/client_side_validations/issues/696
It seems like the easiest solution for you is to use form_for. If you need to use form_with, it seems like the developer may be working on a solution or have one coded on another branch.
Let me know if it works or if you need more help.

How do I get simple_form and bootstrap to work together?

I'm using simple_form to generate my forms in my Rails application. I'm wanting to use bootstrap with these forms. So I've installed the following gems and added them to my gemfile... (1)simple_form, (2)twitter-bootstrap-rails. Finally, per instructions on the simple_form git page I ran, rails generate simple_form:install --bootstrap.
After running bundle install everything is installed and the server runs. The forms however are still not displaying correctly as they would with the class "form-control".
Form
= simple_form_for #user, html: { multipart: :true, class: "form-horizontal" } do |f|
= f.input :headshot_image, as: :file
= f.input :remote_headshot_image_url, placeholder: "Image Url"
= f.input :first_name, required: true
= f.input :middle_name
= f.input :last_name, required: true
I am able to get it to "work" by two different methods (neither of which I believe are correct). First I can add , class: "form-control" to each input, or I can add to the simple_form_for :defaults => { :input_html => { :class => "form-control" } }. The former which kinda defeats the purpose I believe, and the latter works, but it also applies the class to the file input which is not ideal.
Is there a setup step that I missed? Or have I done something incorrect. If I need to provide more information or left something out please let me know. Thanks!
Probably you forgot about adding bootstrap assets to application.css file
simple_form Readme has following line:
You have to be sure that you added a copy of the Bootstrap assets on your application.

How to simply validate a checkbox in rails

How do you simply validate that a checkbox is checked in rails?
The checkbox is for a end user agreement. And it is located in a modal window.
Lets say i have the checkbox:
<%= check_box_tag '' %>
Where and how should i validate this?
I have seen most posts about checkbox validation in rails here, but none of them suit my needs.
Adding
validates :terms_of_service, :acceptance => true
to your model should do it. Look here for more details and options.
However, if accepting the terms is not part of a form for your model, you should use client-side validations, i.e. JavaScript, like this (in jQuery):
function validateCheckbox()
{
if( $('#checkbox').attr('checked')){
alert("you have to accept the terms first");
}
}
You can add a script file to your view like this:
<%= javascript_include_tag "my_javascipt_file" %>
and trigger the function on click:
<%= submit_tag "Submit", :onclick: "validateCheckbox();" %>
EDIT: you can assign an id to your checkbox like this: check_box_tag :checkbox. The HTML will look like this: <input id="checkbox" See these examples for more options.
I was able to skip the jQuery portion and get it validation to work with this questions help. My method is below, I'm on Rails 5.1.2 & Ruby 2.4.2.
Put this code in your slim, erb or haml; note syntax may differ slightly in each.
The line below was specifically for slim.
f.check_box :terms_of_service, required: true
I used a portion of kostja's code suggestion in the model.
validates :terms_of_service, :acceptance => true
Adding on to what has been said already, if you want to add a custom error message, you can add the following to your form:
f.input :terms_of_service, as: :boolean
and then add the following to your model:
validates :terms_of_service, acceptance: { message: "must be accepted"}
Error messages will start with the field name by default followed by your custom message (e.g. Terms of service [CUSTOM MESSAGE]). Something I also found useful was to include a link to the terms of service in the label so users can easily access it to see what they are agreeing to:
f.input :terms_of_service, as: :boolean, label: "I agree to the #{link_to "terms of service", [TERMS AND CONDITIONS PATH]}".html_safe

HAML - how to create form validation and display error messages?

I am able to render a form in HAML but I am not sure how to validate it.
Here is what I have so far:
#disclosure-form-container
= form_for([:mobile,#disclosure], :html => {:id => "disclosure-form", :remote => true}) do |f|
%p
=f.label :display_as, (t :select_disclosure_type)
=f.select :display_as, options_from_collection_for_select(Disclosure.basics, :display_as, :name, f.object.display_as)
%p
=f.label :notes, (t :notes)
=f.text_area :notes, :class => "#{validation_rules(:free_disclosure_notes)}", :rows => 5 , :id => "disclosure_notes_entry"
= buttonset({:submit_label => (t "buttons.influencers.disclosures.create"),:submit_css_class => "call-to-action",:cancel_url => "#",:direction => :left_to_right})
This renders a form with two fields and a button to click submit. But what if people just enter submit without doing much? Where do I put the validation code and how do I validate this form?
Thanks!
A user enters data that should be saved in your model and then stored in your DB. So it's naturally to implement validation on model-level. Rails allows you to create validation for models easy. Here you can read about it. In a few words: adding few lines to your model prevent it to be saved with inconsistent data.
But you can in addition to model-level validation use client-side validation: i.e., data will be checked before sending to server. This way user don't have to submit form to find out that he forgot to fill some required field. But of course this can't be any guaranty as it's easy to bypass. Here more about client-side validation.
So, as you see, Haml can't help you with validations. It's a great tool, but not for this purpose.
In your Disclosure model, you need:
class Disclosure < ActiveRecord::Base
validates_presence_of :display_as, :notes
...
end
Then you can include error messages at the top of your form with something like:
- if #disclosure.errors.any?
%ul.errors
- #disclosure.errors.full_messages.each do |msg|
%li= msg
Or if you use Simple Form you get automatic validation messages inline, and your form would just look like this:
= simple_form_for #disclosure do |f|
= f.input :display_as
= f.input :notes
= f.submit
And you're done.
Note, as Jdoe pointed out, HAML has nothing to do with detecting validations, it only displays what the server tells it. The server is what determines whether there are validation errors.
If you want to try and come up with the equivalent of something like this client side you could give your form an id and do something like this (in CoffeeScript):
jQuery ->
$('form#disclosures').submit (event) ->
unless $('input#display_as').val().length > 0 && $('input#notes').val().length > 0
event.preventDefault()
$(this).append('<div class="error">You must select 'display' and enter notes.</div>')

Customize error message with simple_form

I'm using the simple_form gem. I want to customize the error message displayed when a user fails validations. How can I accomplish this?
You can declare the content of the
error message in your model:
validates_length_of :name, :minimum => 5, :message => "blah blah blah"
You can set id or class for your
error tag:
<%= f.input :name, :error_html => { :id => "name_error"} %>
Then you can use CSS for the styling.
And you can use
<%= f.error :name, :id => "name_error" %>
and you'll get
<span class="error" id="name_error">is too short (minimum is 5 characters)</span>
I dont know if it is any different for simple_form gem.
For content of error messages to be changed, you can use the :message attribute in the model.
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
end
Now the validation message will be Email is not filled up. If you want the field name also to be changed(Email to E-mail address something like that ), the approach now is to define it in locales.rb file like this
# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
See link for details on locales. Another approach is to define in the model, humanized attributes like this:
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address",
...(other fields and their humanized names)
...
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
For customizing style of validation message we will have to edit the style for
#errorExplanation and .fieldWithErrors,in the scaffold.css stylesheet.
You can easily change the default error message comes in the translation file, which is found in config/locales/simple_form.en.yml.
In the specific initializer, config/initializers/simple_form.rb you can overrule the default options how the html is generated.
Hope this helps.
For completeness, I would like to add that formtastic is an easier choice to start with, because it has a default layout. I like simple_form a lot, but it does not offer any formatting out of the box, but that is their intention. With Formtastic it is very hard (impossible) to change the generated html, and with simple_form can you can completely mold the generated html to your liking. This is especially useful if you have a designer, and the forms you generate have to generate the same html. So if you are getting started, formtastic will give you nicer-looking results quicker. Also note that it is quite easy to switch, because the syntax is almost identical.
There is another solution explained here that wasn't mentioned in the answers. You can directly override the error messages from the views, in the form itself. For example:
<%= f.input :last_name,
placeholder: 'last_name',
error: 'This is a custom error message',
required: true,
class: 'form-field',
autofocus: true,
input_html: { autocomplete: "last_name" } %>
It is however not advised as it is not DRY, you would need to override it in every field.

Resources