Validate at least one checkbox is ticked in Rails 5 - ruby-on-rails

I am trying to do a server side validation in Rails 5 and I am having issues. I'm still very much a noob but this has me stumped.
I want to check to see if any of the 4 checkbox options have been ticked on saving.
In my form I have:
<%= f.input :property_type, label: 'List as', as: :check_boxes, collection: %w(Student Graduate Professional Family), checked: property.property_type %>
And I have tried
validates :property_type, acceptance: { message: 'must be selected' } and validates :property_type, presence: true neither have worked.
I've also tried to create a custom validation but I could not get that to work either.
Can anyone please help?

Custom validation should work in your case. could you please check with below snippet?
validates : property_type_is_selected
private
def property_type_is_selected
if self.property_type.blank?
self.errors.add(:property_type, 'must be selected.')
end
end

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.

rails validate specific value

I have this code
I have these options and if the user select anything except 'British Columbia'
to give him error message that the province have to 'British Columbia'
I believe it will solve by using the model validation
<%= f.label :province ,"Province (required)"%><br>
<%= f.select(:province, [["Select One", ""],'Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador','Nova Scotia','Northwest Territories','Nunavut','Ontario','Prince Edward Island','Quebec','Saskatchewan','Yukon'], {}) %>
User.rb
validates :province, presence: "British Columbia"
You shouldn't use presence, it's the wrong validation. You should use inclusion:
validates :province, inclusion: { in: %w[British Columbia] }
You realize this is a nonsensical problem, right? What's the point of offering several alternatives in the view if the validation will only accept one?

validates :terms, acceptance: true not showing error

In my model I have the following validator:
validates :terms, acceptance: true, on: :create, allow_nil: false
attr_accessor :terms
and in my form I have:
= simple_form_for #reservation do |f|
= f.error_notification
= f.input :terms, as: :boolean
The problem is that when user not accept the terms it not showing any error, why?
Try this:
validates :terms, :acceptance => {:accept => true} , on: :create, allow_nil: false
Problem may have terms as an actual column in the table. In general validates_acceptance_of is used without such a column, in which case it defines an attribute accessor and uses that for its validation.
In order for validates_acceptance_of to work when it maps to a real table column it is necessary to pass the :accept option, like:
validates :terms, :acceptance => {:accept => true} , :on => :create , allow_nil: false
The reason for this has to do with typecasting in Active Record. When the named attribute actually exists, AR performs typecasting based on the database column type. In most cases the acceptance column will be defined as a boolean and so model_object.terms will return true or false.
When there's no such column attr_accessor :terms simply returns the value passed in to the model object from the params hash which will normally be "1" from a checkbox.
Via noodl
I may have had a similar problem (Rails 4.2.0). I created a checkbox, but it would be ignored and never report and error if unchecked. I found that adding the parameter to the .permit part of my Strong Parameters allowed it to be present.
In my view template for my _form I have something like this:
<div class="field">
<%= label_tag :tos, 'I accepts the TOS' %><br>
<%= f.check_box :tos %>
</div>
I generated my model using scaffold, so my create method start like this
def create
#thing = Thing.new(thing_params)
then near the bottom I have the following for thing_params
def thing_params
params.require(:thing).permit(:field1, :field2, :tos)
end
in my model I used the following:
validates_acceptance_of :tos
If I leave out ':toslike thisparams.require(:thing).permit(:field1, :field2) it will not pop up an error and allows it to continue. This seems counter-intuitive because if Strong Parameters is removing the :tos field then I would think the validate_acceptance would fail.
I had initially just create a checkbox without using f.check_box. Now, if I even try to call the new route without :tos" being listed as permitted, rails throws an error. There also seems to be some rails magic going on because if I remove the validates_acceptance_of from my model, I receive an NoMethodError error when rendering my view saying undefined methodtos'` for the line
<%= f.check_box :tos %>
Would be great if someone else could explain what exactly is going on as I just hacked this together from googling and guessing.

simple_form doesnt prevent sending request without required fields

i have this form
= simple_form_for #category.fields.build, url: category_fields_path(#category) do |f|
= f.input :kind, collection: Field::FIELD_TYPES, prompt: "Choose field type"
= f.input :description
= f.submit "Add field"
and this field model
class Field < ActiveRecord::Base
FIELD_TYPES = %w(integer float date string text)
validates :description, presence: true
validates :kind, presence: true
belongs_to :category
end
when i leave 'description' field empty, no request is send and i get notice 'Please fill out this field'. which is what i want. on the other hand, when description is filled in but kind is not, a request is still send to the 'create' action! No field gets created, but 'description' needs to be filled in again. there should be no request in such situation. any idea how to fix this?
Though, I don't have exact answer to Your problem, but You should start with checking HTML output. Simple from relies on HTML5 to provide front-end validation. All inputs should have required attribute, to have validation enabled. Maybe there is a bug, and in this particular case simple_form does not output required attribute.
Another thing to take in account as it is HTML5, consult browser support: http://caniuse.com/#feat=form-validation . Theoretically it's possible that You are testing on browser that has limited support for form validations.
If You discover that simple_from did not output required for Your kind fuel, try forcing it:
= f.input :kind, collection: Field::FIELD_TYPES, prompt: "Choose field type", required: true
I got my answer at Simple Form github's issue topichere. to sum up, problem was prompt, validation is not (yet?) working with it correctly, solution is to replace it, eg like this:
= f.input :kind, collection: Field::FIELD_TYPES, include_blank: "Choose field type", label: false

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

Resources