In the new version of jQuery validation plugin 1.9 by default validation of hidden fields ignored. I'm using CKEditor for textarea input field and it hides the field and replace it with iframe. The field is there, but validation disabled for hidden fields. With validation plugin version 1.8.1 everything works as expected.
So my question is how to enable validation for hidden fields with v1.9 validation plugin.
This setting doesn't work:
$.validator.setDefaults({ ignore: '' });
The plugin's author says you should use "square brackets without the quotes", []
http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/
Release: Validation Plugin 1.9.0:
"...Another change should make the setup of forms with hidden elements
easier, these are now ignored by default (option “ignore” has
“:hidden” now as default). In theory, this could break an existing
setup. In the unlikely case that it actually does, you can fix it by
setting the ignore-option to “[]” (square brackets without the
quotes)."
To change this setting for all forms:
$.validator.setDefaults({
ignore: [],
// any other default options and/or rules
});
(It is not required that .setDefaults() be within the document.ready function)
OR for one specific form:
$(document).ready(function() {
$('#myform').validate({
ignore: [],
// any other options and/or rules
});
});
EDIT:
See this answer for how to enable validation on some hidden fields but still ignore others.
EDIT 2:
Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation plugin.
If you're struggling with the unobtrusive-validation plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235
This worked for me, within an ASP.NET MVC3 site where I'd left the framework to setup unobtrusive validation etc., in case it's useful to anyone:
$("form").data("validator").settings.ignore = "";
Make sure to put
$.validator.setDefaults({ ignore: '' });
NOT inside $(document).ready
So I'm going to go a bit deeper in to why this doesn't work because I'm the kind of person that can't sleep at night without knowing haha. I'm using jQuery validate 1.10 and Microsoft jQuery Unobtrusive Validation 2.0.20710.0 which was published on 1/29/2013.
I started by searching for the setDefaults method in jQuery Validate and found it on line 261 of the unminified file. All this function really does is merge your json settings in to the existing $.validator.defaults which are initialized with the ignore property being set to ":hidden" along with the other defaults defined in jQuery Validate. So at this point we've overridden ignore. Now let's see where this defaults property is being referenced at.
When I traced through the code to see where $.validator.defaults is being referenced. I noticed that is was only being used by the constructor for a form validator, line 170 in jQuery validate unminified file.
// constructor for validator
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
At this point a validator will merge any default settings that were set and attach it to the form validator. When you look at the code that is doing the validating, highlighting, unhighlighting, etc they all use the validator.settings object to pull the ignore property. So we need to make sure if we are to set the ignore with the setDefaults method then it has to occur before the $("form").validate() is called.
If you're using Asp.net MVC and the unobtrusive plugin, then you'll realize after looking at the javascript that validate is called in document.ready. I've also called my setDefaults in the document.ready block which is going to execute after the scripts, jquery validate and unobtrusive because I've defined those scripts in the html before the one that has the call in it. So my call obviously had no impact on the default functionality of skipping hidden elements during validation. There is a couple of options here.
Option 1 - You could as Juan Mellado pointed out have the call outside of the document.ready which would execute as soon as the script has been loaded. I'm not sure about the timing of this since browsers are now capable of doing parallel script loading. If I'm just being over cautious then please correct me. Also, there's probably ways around this but for my needs I did not go down this path.
Option 2a - The safe bet in my eyes is to just replace the $.validator.setDefaults({ ignore: '' }); inside of the document.ready event with $("form").data("validator").settings.ignore = "";. This will modify the ignore property that is actually used by jQuery validate when doing each validation on your elements for the given form.
Options 2b - After looking in to the code a bit more you could also use $("form").validate().settings.ignore = ""; as a way of setting the ignore property. The reason is that when looking at the validate function it checks to see if a validator object has already been stored for the form element via the $.data() function. If it finds a validator object stored with the form element then it just returns the validator object instead of creating another one.
This worked for me within an ASP.NET site.
To enable validation on some hidden fields use this code
$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";
To enable validation for all elements of form use this one
$("form").data("validator").settings.ignore = "";
Note that use them within $(document).ready(function() { })
Just added ignore: [] in the specific page for the specific form, this solution worked for me.
$("#form_name").validate({
ignore: [],
onkeyup: false,
rules: {
},
highlight:false,
});
This is working for me.
jQuery("#form_name").validate().settings.ignore = "";
The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.
To fix this I added the following to manually trigger the jquery validation event that gets added by the library:
$(".chosen-select").each(function() {
$(this).chosen().on("change", function() {
$(this).parents(".form-group").find("select.form-control").trigger("focusout.validate");
});
});
jquery.validate will now add the .valid class to the underlying select list.
Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group, and each input has .form-control.
Just find the text ignore: ":hidden" in your jquery validation file and comment it.
After comment this it will never loss any hidden elements to validate...
Thanks
Related
This question already has answers here:
onkeyup and onfocusout is not working in jQuery Validate
(1 answer)
jQuery validate plugin: validate on blur() by default
(1 answer)
Closed 5 years ago.
I'm making a "contact me" page, with jQuery validation. My main content box is reloaded with ajax to change content when the user clicks on a new page. The problem I'm having now is to bind an event handler for the validate function. what I got now is
$(document).ready(function(){
$('body').bind('focus focusout keyup', function() {
$('#contact_me').validate({
But it's not working like intended. I have to start typing, then click out of the input field and then click on it again before it starts to validate the input field value. I want it to validate on focus, focusout and keyup. I think the problem is with the event handler somehow. Any suggestions?
Here is a JSfiddle with the script: https://jsfiddle.net/z6h9d028/4/
I can see now that the eventhandler is not the problem. When i type in a input field its not validating the value until i click out of the box. After the first validation i works on keyup as well. How can i get i to work on keyup stright away?
Edit 2:
Updated fiddle: https://jsfiddle.net/z6h9d028/7/
It's almost working now! I just need to get all the error messages to show when clicking the submit button. And to find a way to show the error message when you type one character and then remove it if the input field is required (it does show it if you type once, then remove, type again and remove. but not the first time)
You don't need to set your own event listeners, or at least if you do, you shouldn't be using them on the .validate() method (see alternative method below).
Remove the whole $('body').bind() part, and add the following to your validate settings object:
onkeyup: function(element) {
$(element).valid();
// As sparky mentions, this could cause infinite loops, should be this:
// this.element(element);
},
This should be better too, as it may give you some extra freedom as to how you handle the onkeyup events, such as adding a setTimeout if you don't want it to be instantaneous.
Fiddle: https://jsfiddle.net/z6h9d028/5/
Inside the onkeyup, you can also call $('#contact_me').valid(), which will revalidate the whole form, although that may not be your desired outcome.
Edit: Sparky also helpfully mentioned that jquery-validate by default does allow keyup events, but it only does so after the first submit: jQuery validate plugin: validate on blur() by default
An alternative way would be to set the details of your validation as you currently are, without the onkeyup function, then set your own listeners and run $(element).valid():
$('#contact_me').validate({
rules: {
// ...
}
});
$('input').on('focus focusout keyup', function () {
$(this).valid();
});
Edit regarding your other issues:
Your errorPlacement function is doing some funky things. How it decides what is the next sibling or not seems to be working incorrectly. Also, you're adding the error HTML divs into your DOM manually, but they are actually generated by the plugin. So really, you're creating both, then trying to show them, kinda over-riding the plugin, kinda not, and the whole thing is going into a frenzy.
The solution is, I reckon, to remove those error divs, remove that errorPlacement function, and then modify the CSS selectors to get any id ending with "-error", which is what the plugin generates. So [id$='-error'] instead of .error_message
https://jsfiddle.net/z6h9d028/8/
I'm using this: $('form').dirtyForms(); from https://github.com/snikch/jquery.dirtyforms to check if my form is dirty. However, on my page I have some dropdown's that are simply used for filtering (they should not make my form "dirty"). Right now when I select any of these drop down's it causes my form to become dirty. Using jquery.dirtyforms (I read their docs but do not see how), how do I exclude selectors (dropdowns, textboxes, etc.) maybe via a class name so that they do not mark the form as dirty.
I tried various things like assigning these dropdowns / filters a class called ignoreDirty then in my jquery I did this:
$('form').dirtyForms().ignoreClass('ignoreDirty');
This produces an error, so I must be doing something wrong.
Note I've also tried setting it via property:
$('form').dirtyForms({ ignoreClass : "ignoreDirty" });
But this still makes my form dirty for any control whose class name is still ignoreDirty
Please note these filters cause postbacks but lets say I go to my form and have not made a single change. I start clicking on these filters and the minute they post back this happens:
What can one say, the plugin code makes almost no sense to me :D However to make it quickly work for ignoring select boxes, you could replace its onSelectionChange with following
Original function
var onSelectionChange = function() {
$(this).dirtyForms('setDirty');
}
New version
var onSelectionChange = function () {
//this is the new line. self explanatory
if ($(this).hasClass($.DirtyForms.ignoreClass)) return;
$(this).dirtyForms('setDirty');
}
After this you should rely on the original developer for a proper fix. I just posted this as an answer because of space in comments
There seems to be 2 different issues here.
First of all, you are attempting to set the ignoreClass to ignoredirty. ignoredirty is the default value, so there is no reason to set it. However, if you do need to set it to something else, you can do so using the syntax:
$.DirtyForms.ignoreClass = 'my-ignore-class';
Secondly, in version 1.0.0 the ignoreClass only worked on Hyperlinks. This behavior has been amended to work with input and selection elements in version 1.1.0.
In version 1.2.0, you can now also set the ignoreClass to parent container elements to ignore input or clicks from any element within.
I am using CKEditor, it works fine but it turns out that there is a problem with validation. I am using this trick:
$('input[type=submit]').bind('click', function () {
var ckContent = CKEDITOR.instances.Content.getData();
$("#Content").val(ckContent);
});
To make validation work, but it doesn't help at all. I mean, when I send a form, it binds value to a textarea, but jquery doesn't want to validate this. When I turn off CKEditor completely, validation works fine on pure textarea. So what is wrong? How can I make CKEditor work with ASP.NET's validation?
I'm thinking the input select is happening too late to be validated. So I think you need to update the text box after you blur the CKEditor.
var editor = CKEDITOR.replace('content');
editor.on('blur', function (e) {
$("#Content").val(this.getData());
});
EDIT: I'm assuming you're trying to get a required field validator to fail/pass. I forgot CKEditor will place <p> tags even if there is no content (by default). On your submit button click, try forcing an update:
$('input[type=submit]').bind('click', function () {
CKEDITOR.instances.Content.updateElement();
});
SECOND EDIT: By default, jQuery validation does not validate hidden fields. To override that feature with MVC's unobstructive javascript add $.validator.setDefaults({ ignore: '' }); right after the includes for the validation. This will allow all fields to be validated on the page.
I currently have two of the same contact forms being used on a webpage. One is on every page- in the banner, and another version of it is in the main section of the contact page itself. This is what I use to validate it:
$(".contactform").each(function() {
$(this).validate();
});
However, when I click submit on either of the forms, the opposite one of it (the unused one) comes back showing errors. I don't want the person to have to fill in both (as they are the exact same form) and am a bit confused on where to go from here.
What I ended up doing according to xnnyygn's answer was adding in separate .validate rules by id, when done by class or form this would not work and exhibit first selection error result.
$("#contactform1").validate({
rules: {
field: {
required: true
}
}
});
$("#contactform2").validate({
rules: {
field: {
required: true
}
}
});
$(document).ready(function(){
$("#contactform1").validate();
$("#contactform2").validate();
});
I ended up using two ids instead of a class or form selector here. Doing otherwise will not work. Lesson learned, with jquery.validator you must use ids.
This is my test HTML, from http://docs.jquery.com/Plugins/Validation#source, adding a duplicated form with same class.
I've tried to call validate directly, but the first form was validated when I press the second submit button. However, calling validate separately works well.
The reason why validator 'jumps' to another form may be that jquery validator only take the first element(form) and apply the rules. See the source for more detail.
Not sure if it solves this problem, but you shouldn't need to use '.each()' explicitly. Just write:
$(".contactform").validate();
I want to use jQuery Validation Plugin with jQuery UI Tabs. How I can validate using jQuery Validation Plugin on each step triggered by next button. I see examples of jQuery Validation Plugin and mostly are for validation of whole form at once. I need it step by step.
I am not a pro so please tell me some easy solution instead of suggesting me other plugins. My code looks like:
$("#frag1").click(function(){
//I need jQuery Validation code here for a single step
event.preventDefault();
}else {
$('.next-tab, .prev-tab').click(function() {
$tabs.tabs('select', $(this).attr("rel"));
return false;
});
}
Thanks in advance.
I realise that you didn't want suggestions for other plugins. But I think this could be especially useful for you:
There is the jQuery formwizard plugin, http://thecodemine.org/
Which integrates nicely with the jquery validation plugin. And also is themeable with jQuery-UI themes (if you are already using them on your site).
On next step button click check for which fragment div did not have "ui-tabs-hide" this css class. Then try to apply same CSS class (e.g:- "myinputs") for all inputs and checkbox and soon. Then apply validation for current "fragment" div inputs validation.
For example:-
if I am in step 2. Then this div "fragment-2" won't have css class "ui-tabs-hide". You can see that class applied to other dives.
So, try to get current active div ID (here it is "fragment-2"). Then do like this
http://docs.jquery.com/Plugins/Validation/Validator/element#element
$("#myform").validate().element( "#myselect" ); // here there are passing element ID
$("#myform").validate().element('#'+ CurrentFragment + '.myinputs'); //here we are passing current fragment css class inputs.
I am not sure it will accept css class. But try once else loop and handle false element and return false with out any step. So, user won't move to next fragment until he set values.
I not sure this is best idea. I don't have much knowledge about that validation plugin.