问题
I am using the client_side_validations gem with Rails 3.1.0. I have been trying to use it to validate a hidden field that is set through a javascript widget. From what I have read on the gem's github page, the gem deliberately does not validate hidden fields because the user could not correct these fields. I have unsuccessfully tried to override this behavior.
Is there a way to override this behavior for a particular field without modifying the client_side_validations code (other than the init stuff that gets generated when you install the gem)?.
The way I've done it now is by making a slight modification to the validateForm function in the gem. When it looks for the fields to validate it only grabs the elements that are visible:
form.find(':input:enabled:visible[data-validate]').each(function()
So I changed that to this:
form.find(':input:enabled[data-validate]').each(function()
This seems to work. Is there a better way?
I haven't been able to re-validate the hidden field when the user corrects their mistakes.
回答1:
If you want to validate hidden fields that is how to do it
回答2:
@mushroom asked about client_side_validations version 3.1, but for anyone using version 3.2.x, this is now configurable.
This code on 3.2-stable branch shows how it's done.
You will need to override window.ClientSideValidations.selectors.validate_inputs
and window.ClientSideValidations.selectors.inputs
once the page loads. As for including validations for the hidden element in the hash, my recommendation is to load the page with the element visible, and immediately run $('#id_of_hidden_element').attr('type', 'hidden')
.
Alternatively, you can just make the input element type='text'
and use opacity:0
in a CSS stylesheet to make it invisible. Note that this has other side-effects, such as making it focusable.
回答3:
I think better way is validate it by adding 'id' or 'class'
<input type="hidden" id="validate_me">
then selector should be like this:
':input:enabled:visible[data-validate], #validate_me'
来源:https://stackoverflow.com/questions/14186916/override-client-side-validations-behavior-to-validate-hidden-fields