I am trying to validate a form with jquery validation but it does not show the expected error message. How can I set it so it show my messages?
here is the javascript that I am using:
$(function () {
$("#registerForm").validate({
rules: {
inputEmail: {
required: true,
email: true
}
},
messages: {
inputEmail: "Please enter a valid email address"
}
});
});
Please have a look at the jsfiddle link of my code:
JSFIDDLE code with html/bootstrap *Updated
On the live version of my site it does not even show the popup message that is appearing in jsfiddle. Please help me in fixing this.
Ideally I would like to display inline messages or a summary if validation fails but don't know how to do this. I was hoping if jquery validation works then I would be able to specify custom functions to handle success and error events.
I would appreciate if someone can help me out here. Thanks.
UPDATE
Notice how you still have this issue even after I've removed jQuery and jQuery Validate from the jsFiddle?
http://www.jsfiddle.net/xRRZb/4
The pop-up bubbles and over-riding messages are generated directly by the browser thanks to HTML5... nothing to do with any of your JavaScript or jQuery code.
So since you've already defined the required and email rules within .validate(), remove required and type="email" from your inline HTML:
<input type="text" name="inputEmail" id="inputEmail" placeholder="E.g. youremail#website.com" />
DEMO: http://www.jsfiddle.net/xRRZb/6
EDIT:
jQuery Validate 1.8 is quite old. Consider upgrading to version 1.11.1
In fact, this is likely your whole problem. Version 1.11.1 dynamically adds a novalidate="novalidate" attribute to the form tag to disable HTML5 validation when the plugin is being used.
Unfortunately, version 1.8 does not have this feature.
Alternatively, you could manually add the novalidate attribute to ensure that you disable HTML5 validation. However, if you manually add the novalidate attribute, there will be no fallback.
Related
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
I've seen bunches of questions about this, but wanted to clarify my understanding. It all started when I was setting up jQuery validation on a popup form. If I added the validate() method while the form wasn't visible, the validation didn't work (straight submit). If I added validation after the form element was visible, all is well... the validate fires and doesn't submit the form.
So, I tried to isolate this behavior and this is what I ended up with:
https://jsfiddle.net/KyleMit/ph8ue5j5/
Here's the HTML:
<form id="form" style="display: none;">
<input type="text" name="name" id="name" placeholder="Name" required="requited" /><br/>
<input id="submit" class="button" type="submit" value="submit"/>
</form>
Here's the JS:
$(function() {
$('#form').validate({
rules: {
name: {
required: true,
minlength: 2
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "Name should be more than 2 characters"
}
}
});
window.setTimeout(function() {
$("#form").show()
}, 3000);
});
If you run this, you will see the form is first invisible. Then after 3 seconds, becomes visible. This is the same setup as my popup form.
What surprises me is the validations works! This goes against what I have been reading and what I've witnessed in my web project.
Can anyone explain this?
It depends on which version you're using. As of version 1.9.0, ignore: ":hidden" is the default option, so it doesn't need to be set explicitly. Depending on when you were looking at answers or which version you were using, you might see different answers.
In your example, you're using v1.11.0, so hidden elements should be ignored by default. The :hidden selector includes elements that:
have a display value of none.
are form elements with type="hidden".
have width and height are explicitly set to 0.
have an hidden ancestor, so the element is not shown on the page.
If you want to change that, you need to pass in a different value for ignore in the options object.
The point that seems to be causing confusion is at what point the validation check if an element is hidden. When a form submits, jQuery-Validate will re-check any inputs. It's at that point that elements in your ignore will be chosen or not. So if an element is visible by the time you're hitting submit, it will be validated.
Try running the sample below. If you submit before the first element has a chance to load, you'll only get a single warning, even though both inputs are required, because the first one is excluded because it's hidden. Wait until the script shows the first input and try to submit again, and both elements will be included.
Demo in Stack Snippet
$(function() {
$('#form').validate({
ignore: ':hidden'
});
window.setTimeout(function() {
$('.hidden').show()
}, 4000);
});
.hidden {
display: none;
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.min.js"></script>
<form id="form" >
<input type="text" id="hidden" name="hidden" placeholder="Originally Hidden" required="required" class="hidden" /><br/>
<input type="text" id="visible" name="visible" placeholder="Originally Visible" required="required" /><br/>
<input type="submit" id="submit" value="submit"/>
</form>
"This goes against what I have been reading and what I've witnessed in my web project."
Unfortunately, you did not provide an example of this alternative behavior you're describing. We can only see your demo, which is working exactly as designed.
Can anyone explain this?
Not until you show us the broken version.
$('#form').validate({ ....
You can attach the .validate() method to a hidden form and the plugin will be ready to validate this form. As long as the HTML exists when you call .validate(), the plugin is initialized and ready for form validation.
If the form fields are hidden OR if the form fields are inside a hidden container, there will be no validation on these fields. HOWEVER, this will not prevent you from initializing the plugin on the form as described in #1 above. Simply making the fields visible (in this case the whole form) allows them to be validated.
You can optionally validate hidden fields by setting the ignore option to []. However, I don't believe you're asking about how to validate hidden fields.
Quote OP Comment:
What I'm seeing in my project is if the form is hidden when the validate() method is called, and the form becomes visible, it still won't validate. But if I call the validate() method after the form is visible, it works.
The demo you've provided is showing the exact opposite of what you describe.
My demo below is a variation of yours. The .validate() method is attached to a hidden form. Then when you click the button to show the form... validation is already working.
DEMO: https://jsfiddle.net/1v35f7L2/1/
FWIW, make sure you're using the latest version of jQuery and the jQuery Validate plugin. Your demo is using jQuery 1.6, which is several years old and jQuery Validate 1.11, which is also a little old.
I have spent several hours trying to get this issue to work, but I am getting nowhere fast, so I am hoping some one can assist me. I have tried many attempts, searched StackOverflow and Google.
I have a form with a textarea. I have implemented parsley.js on to a form. The parsley validation is working fine, until I add in the CKEditor to the textarea.
The issue I have is that the parsley error message persists (is always displayed) when I submit the form with no value in the CKEditor, even after I enter characters into the CKEditor.
How do I clear the parsley error message when entering data into the CKEditor
I think the reason is that there is no onKeyUp action on the textarea, because the onKeyUp action is now operating on the CKEditor and the textarea is hidden, but then not being able to remove the parsley required error message when I enter data into the CKEditor is killing me.
Here is my form:
<form id="details_form" class="form-horizontal" method="post" data-parsley-validate>
Here is the textarea code:
<p>
<textarea rows="10" data-parsley-required="true" data-parsley-maxlength="5000" data-parsley-required-message="This field is required." id="id_field" cols="40" name="field" data-parsley-id="8686" dir="ltr"></textarea>
<span class="parsley-errors-list" id="parsley-id-8686"></span>
</p>
Any help would be great.
I had the same problem. So here is the solution ;)
HTML:
<textarea id="ckeditor" data-parsley-required="true" data-parsley-required-message="This field is required" rows="6"></textarea>
JS:
CKEDITOR.replace( 'ckeditor' );
CKEDITOR.config = {
autoUpdateElement: true,
}
CKEDITOR.on('instanceReady', function(){
$.each( CKEDITOR.instances, function(instance) {
CKEDITOR.instances[instance].on("change", function(e) {
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
});
});
});
Edited due to comment by mightyspaj:
CKEditor does not actually operate ontop of the textarea element. The element gets replaced by an iframe to provide the UI. This problem sounds like the textarea is not being updated properly.
I suggest that you access the textarea by JavaScript and manually trigger different events on it to see if the validation message changes due to those triggers. Parsley might have the events it listens to documented somewhere.
When you find for sure the offending event, simply bypass the automation and fire it yourself. If you need live refreshing do for example a 1second setInterval to trigger the validation.
Old answer:
Sounds like you want the autoUpdateElement configuration setting: http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-autoUpdateElement
CKE does not operate directly on the textarea, it creates an iframe and does some other magic. So, the underlying element needs to be updated. You can do this manually using the updateElement() function or you can try autoUpdateElement setting above.
I am using Jquery Validate plugin for a form. Everything works fine except if I tab to the submission button it changes the text color. I have tried using the "ignore:" option then specify the class of the submission button in the validate() function but this doesn't work.
$("#edit_phone_form").validate({
ignore: ".orange-button",
rules: {
phone_number: {
required: true,
phoneUS: true
}
}
});
If anyone knows how I can tell Validate to ignore the ".orange-button" class please let me know. I have no code that is manipulating this button so I know Validate is doing something since it does this same text effect with all other form elements.
Thanks!
Quote OP:
" have no code that is manipulating this button so I know Validate is doing something since it does this same text effect with all other form elements."
There is absolutely nothing in the jQuery Validate plugin that is affecting the color/look/style of your buttons... nothing at all. Even when the plugin adds or removes classes on validation, it does not contain any CSS properties, nor does it manipulate any CSS properties, period.
Furthermore, the plugin doesn't validate buttons since they have nothing to do with entering data into the form. The plugin only validates the various "data input" elements, text boxes, text areas, select lists, radios and checkboxes... and nothing else. Then if the form data passes/fails validation, a success/error class is applied to the element along with a new element containing an error message.
Here is a demo with what you've described in your OP: http://jsfiddle.net/5vFCg/
<input type="submit" class="orange-button" />
As you can see, the submit buttons are rendered as default browser buttons, and their look is totally unaltered from the browser default, proving that jQuery Validate is doing nothing to these buttons.
You must have overlooked something. Show enough code to create a demo of what you're seeing.
Until now I was using the following to disable/enable form fields -
$('#fieldid').attr('disable','disable');
$('#fieldid').removeAttr('disable');
And that got the job done. But yesterday, I absent-mindedly typed the following to enable the field -
$('#fieldid').enable();
And it worked! I silently kicked myself for not trying the the handy 'enable'/'disable' functions built into jQuery (or so I thought), and proceeded to change the line to disable to -
$('#fieldid').disable();
And to my surprise, that did NOT work.
Am I missing something? Why is the enable() function defined but the disable() function is not? And even weirder, I could find no mention of either enable() or disable() in the jquery docs. Does anyone have any explanations?
I'm using jQuery 1.6.
jQuery does not support an enable() method out of the box (and the disable HTML attribute does not exist either, but that might only be a typo in your question).
Maybe you're using a plug-in that provides that feature? If that's the case, try passing false to the enable() method to disable a field:
$('#fieldid').enable(false);
Looks like it's available via the disable plugin. As for why it's not included out of the box, I can only assume that it was left out as the functionality was already covered by .attr()
I have read through the jquery code and the documentation but couldn't find any indicition of am enable function, are you sure the box isn't already enabled?
I created a jsfiddle to check:
http://jsfiddle.net/Zy3tW/1/
$(document).ready(function(){
$("#textinput").enable();
});
<input id="textinput" type="text" disabled="disabled" />