How do I validate a jQuery datepicker field using the Rails client_side_validations gem? - ruby-on-rails-3

I'm trying to get a jQuery datepicker instance to validate with client_side_validations and not having any luck.
Anytime I include this in my model
validates_presence_of :due_date, :message => "Please select the due date"
The form just doesn't submit - no JS error, no log entry from Rails.
When I remove focus from the field without a value I do get the error message, so I know it's working at least a little bit.
Just can't figure out how to get the form submitting.
Thanks.

Seems to me CSV is hijacking the form before POST, because it doesn't pass, which makes sense. Do you have a :validate => true on the field itself, and are you using callbacks to generate a message? Because without them, it seems CSV will just reject the POST silently. Also, thinking about it, I've had a similar problem with select boxes and CSV, where no "field_with_errors" can be generated. Also, it's possible that the datepicker JS is conflicting with CSV.

Related

Recaptcha ambethia - Input error: k: Format of site key was invalid / invalid-request-cookie

The error in the title is visible only in firebug. Everything from where I put the recaptcha element on down, is not shown on the page, though is present in the page-source (Mozilla and Opera) - though no error is shown in firebug.
So far, based on others solutions, I have tried reversing the keys (public and private, though they are clearly identified), generating a global-key-pair and using those, and even hard-coding the values into the recaptcha.rb initializer file versus using system-vars. No luck in any cases in dev or production. Also tried suppressing the 'noscript' part, with no change.
The Gem-Generated Page Source reads:
<script type="text/javascript" src="//www.google.com/recaptcha/api/challenge?k=[" mypublickeyhere", "myprivatekeyhere", false]&lang="></script>
<noscript>
<iframe src="//www.google.com/recaptcha/api/noscript?k=["mypublickeyhere", "myprivatekeyhere", false]" height="300" width="500" style="border:none;"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/></noscript>
Why is my private key visible in the page-source? All that code comes from putting this in my view:
<%= recaptcha_tags %>
Edit: Made some progress, many hours in, by force-feeding the keys in the form and controller with:
<%= recaptcha_tags :public_key => 'mypublickeyhere' %>
and
if ( verify_recaptcha :private_key => 'myprivatekeyhere' )
Which gets the recaptcha to show up on the form, and keeps my private-key from being spammed to the page-code by the plugin as it does in 'default' mode.
Unfortunately, even if captcha is entered correctly, we get a NEW Error, "invalid-request-cookie".
Is there a single example of using this plugin in Rails 3, with full working form and controller code?
More Info for other sufferers:
Google Says this error means: "The challenge parameter of the verify script was incorrect."
On another page, if you search for "challenge parameter," to find out whatever that is, Google says: "recaptcha_challenge_field is a hidden field that describes the CAPTCHA which the user is solving. It corresponds to the 'challenge' parameter required by the reCAPTCHA verification API."
So why is the plugin not providing the correct challenge parameter as it should? Perhaps I need to pass something somewhere - but what and where? Again, a simple example would be great.
0.0. Setting the Variables - an aside:
Use ENV['key'] to keep your keys out of the codebase (though you can hardcode them in /config/environments/development.rb and then not include this file on your production server (for Heroku, add to gitignore in your push folder).
I added this to my development.rb file
# Set variables for Recaptcha on Localhost
ENV['RECAPTCHA_PUBLIC_KEY'] = 'mypublickeyhere'
ENV['RECAPTCHA_PRIVATE_KEY'] = 'myprivatekeyhere'
You will put your real key values in place of mybpublickeyhere and myprivatekeyhere.
You could also set ENV variables on your dev-machine. I prefer not to add that clutter, as this machine is used to develop many sites at once.
If deploying to Heroku, learn how to set these ENV variables here:
http://devcenter.heroku.com/articles/config-vars
1.0 Get a set of global-keys, not tied to any particular domain, and use these for testing. After eliminating that potential problem, when all is working, put in your domain-specific keys, on your production machine, and re-test.
2.0 Don't use the 'default' method. From what I can tell, it simply does not work - maybe it once did and Google changed something - I don't know, but it may/will give you the dreaded "Input error: k: Format of site key was invalid" AND will reveal your private key to anyone who views the page-source.
The solution is to force-feed the keys into the form and controller. So, in your form this will look like:
<%= recaptcha_tags :public_key => ENV['RECAPTCHA_PUBLIC_KEY'] %>
3.0 In your controller you will test for true; but again, force-feed the private key like this:
if ( verify_recaptcha :private_key => ENV['RECAPTCHA_PRIVATE_KEY'] )
... your success code here
else
... your fail code here
end
4.0 Placement of the tag in the form is important. The Devise docs refer to this gem, and provide actual example code of using this gem:
http://github.com/plataformatec/devise/wiki/How-To:-Use-Recaptcha-with-Devise
They say to put the recaptcha_tags immediately above the submit button code. This is important. I had to put it within:
<div class="form-actions">
... along with the button
Other sources report that surrounding HTML can break things in mysterious ways, so you may have to experiment for awhile (hope you don't have deadlines, or anything). These 'placement' issues were the culprit with the 'invalid-request-cookie' error I received.
I hope these guidelines shorten your development time.

Model paper clips validations errors are not displayed in simple_form

I am using paper_clip and simple_form gems. Unfortunately, it seems that paper clip validations errors are not displayed in my form.
I have try several types and syntax of paper_clip content_type validations and even they work (the uploaded files types are restricted) no error is displayed in the form.
Has anyone knew know how to fix this?
Here's what I suspect - the paperclip validation is likely being made on an attribute that's not actually an input in simple_form.
You might have something like this in your form:
<%= f.input :picture, :label => "Picture" %>
But paperclip's validation errors aren't going to be put on 'picture' - they'll be put on another attribute, like 'picture_file_name'. Since simple_form has a 'picture' input, and not a 'picture_file_name' input, it doesn't know where to put the errors, so they don't show up.
Take a look at your errors array and confirm what attribute's getting the errors. Then use simple_form's errors helper in your view to put that attribute's error in the appropriate place:
<%= f.error :picture_file_name %>
Unfortunately paperclip provides own format for validation errors storing them in 3 different attributes without linking to base model attribute:
*_file_name, *_file_size, *_content_type
Therefore simple_form or any other form view helper could not map paperclip validation errors with field name.
You can patch paperclip like described here http://dev.mensfeld.pl/2013/05/paperclip-bootstrap-and-simpleform-working-together-on-rails/ and forget about this issue forever

Persist CMultiFileUpload selection through input validation

I'm using a CMultiFileUpload control in one of my forms like this:
$this->widget('CMultiFileUpload', array(
'name' => 'neueAnhaenge',
));
When input validation for some other form element fails and the input form is rendered again, a previous selection in this control is gone (as expected).
How do I repopulate this control, what do I have to do in my controller, is there a way to prepopulate this?
Thanks in advance.
For file fields it is rather impossible to reset the values assigned to it after it has been sent to the server.
One way to solve this would be to get the uploaded files, store them temporarily on the server and modify the form so it sends a reference to the file on the server.
A much better way would be to use Ajax or Client side validation of form fields to ensure no validation error occures when form has been sent. You can enable these options for CActiveForm: $enableClientValidation and $enableAjaxValidation.

Remote AJAX call when checking a ceckbox in Rails 3

If I have a checkbox in Rails3, How can I perform a remote AJAX call when the user changes the value of it.
It sound like a simple task, but I fail to find a good solution for it.
You can pass the value of check-box on change event to the form and by using :remote => true you can use AJAX in form_for.syntax of on changing the check box and submitting the form is ":onchange => "this.form.submit()
I hope this would help you.
Thanks.

Use JS to change <form> from remote to non-remote in Rails 3, HAML

The problem is that i have a remote form that, based on condition, id like to convert to a non-remote form (using UJS), and then submit.
note the form has a file upload.
Here's the details: I have initially rendered the remote form using
= form_for #myobj, :url => {:action=>"remoteAction", :controller=>"myobjects"}, :remote => true do |f|
... (f.fields....)
which produces the HTML:
<form id="new_myobj" class="new_myobj" method="post" accept-charset="UTF-8" data-remote="true" action="/remoteAction">
when i click submit, as expected, the form is submitted 'AS JS'.
in the controller action, i am doing some validation of the fields inside the submitted form.
If all the validations pass, i execute the following .js.haml template:
$('form#new_myobj').removeAttr("data-remote");
$('form#new_myobj').attr('enctype', 'multipart/form-data');
$('form#new_myobj').attr('action', '/myobjects/regularAction');
which successfully changes the HTML on the page (witnessed via Firebug) to:
<form id="new_myobj" class="new_myobj" method="post" accept-charset="UTF-8" enctype="multipart/form-data" action="/myobjects/regularAction">
since the form contains an f.file_field, i have to submit as multipart so the image can be uploaded, and i cannot submit 'AS JS'
now, when i click submit, the controller action 'regularAction' is indeed called, but its still 'AS JS'
the question is, what else do i need to change in the HTML so the form can be submitted non-xhr? is it related to the headers?
jQuery is a bit tricky with the data attributes since it both
reads the HTML5 data tags as well as its own storage bound to the
DOM element, that is also called data. When writing to an attribute
that value gets copied into jQuerys own data storage (presumably
when data("remote") is being called).
However, this only happens
if jQuery’s data is empty for that name. Thus setting the attribute will only work once, after that the "cached" value is being used
even if the attribute changes. In order to really get rid of the
value, we need to remove the attribute and jQuerys own storage
method in that order. The reason is that there’s a high-level
(element.removeData(…)) function and a low level one (jQuery.
removeData(element, …)). The former re-reads the HTML5 data
attribute and stores it in jQuery’s own storage. Using the rather
unusual low level function obviously works as well.
Also, we do really need to remove the attribute -- setting it to
false is not enough since Rails only checks if form.data('remote')
is not undefined (look for it in jquery_ujs.js).
TL;DR:
attr("data-remote") != data("remote")
These two lines make a form non-remote (again). Order matters.
$("form").removeAttr("data-remote");
$("form").removeData("remote");
It’s documented, if you actually know what you’re looking for:
http://api.jquery.com/jQuery.data/ (low level function)
http://blog.madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html
StackOverflow doesn’t allow me to post more than two links, but you can guess the removeData one. The high-level functions are linked from the low level ones.
Avoiding the token authenticity error in Rails 4+:
As Stan commented below, just doing the above will fail with an InvalidAuthenticityToken error. The workaround is easy though, see here for details: https://stackoverflow.com/a/19858504/1684530
The problem is that your approach to disable the Ajax submission isn't quite correct. You need to unbind the JavaScript events that have already been added by rails.js (Rails UJS adapter) to the form.
You can do that by:
$('form#new_myobj').unbind() to unbind all events attached to the form. You also need to $('form#new_myobj').removeAttr('data-remote') and $('form#new_myobj').removeAttr('data-type') to remove data-remote and data-type attributes (if existent).