jQuery plugin: Validation
This jQuery plugin makes simple clientside form validation trivial, while offering lots of option for customization. That makes a good choice if you’re building something new from scratch, but also when you’re trying to integrate it into an existing application with lots of existing markup. The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 36 locales.
The plugin is written and maintained by Jörn Zaefferer, a member of the jQuery team, lead developer on the jQuery UI team and maintainer of QUnit. It was started back in the early days of jQuery in 2006, and updated and improved since then.
Current version: 1.9.0
Minified filesize (even less with GZip): 21,601 bytes
License: MIT/GPL
Files:
Download
Changelog
Demos
Documentation
GitHub Repository
GitHub 1.9.0 Tag
1.9.0 files on Microsoft’s Ajax CDN (hotlinking welcome):
- http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js
- http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js
- http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js
- http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.min.js
- Localization Files at http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/localization/messages_##.js where ## is the loc code.
- vsdoc file for VisualStudio
Dependencies
Required
Optional
- form plugin for AJAX submit
Support
- Please post questions to the official Using jQuery Plugins Forum, tagging your question with (at least) “validate”. Keep your question short and succinct and provide code when possible; a testpage makes it much more likely that you get an useful answer in no time.
- Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

Hello,
Seems that dowload link doesn’t work… I would like evaluate the validation plugin it seems very impresive!!!
Hi Oscar,
just fixed the download, sorry for the inconvience.
Robust, flexible, and built with JQuery. Excellent work, and nice upgrade!
Congrats for this great jQuery plugin. Only one question: how to insert validation rules for dependent fields? Example: a form haves 2 radio options: single and married. If user checks married a select field with numbers from 0 to N is toggled. That 2 fields: married and numbers of childs need to validate for your dependency. Suggestions? Cheers.
Hi Marco,
so far that isn’t supported. Thanks for bringing it up, your example is a good starting for implementing this support (that’s why its still alpha).
So, could you please explain in more detail how the validation should work?
Once married is chosen, the user has to select something in the select field? Is that it? Or something else?
Already got an idea how to implement that
Hi Jorn, I’m sending you a regex to validate in Brazilian(Portugal, Argentina and another South America countries) dates:
Works fine for example: 15/05/2006 OK and 05/15/2006 ERROR
Best regards
Question:
I have this code:
When I load the page I execute this method, then I would like have a button to execute the validation:
Thanks in advanced and Congratulations for this plugin!!!
@Marco: Thanks for the code. I’m thinking about either adding it to the library or providing a little repository of additional validation methods. Currently I tend to the latter, so once someone needs a method that isn’t in the distribution, and can get if from the repository.
@Oscar: Your example is a bit incomplete. I’d need to see the HTML you are using, and a more detailed explanation about what you’d like to achieve.
Hi Jorn
My html is:
.
.
function createValidation() {
jQuery(document).ready(function() {
jQuery(“#DB”).validate( {
event: “custom”,
rules: {
tFieldRef: { required: true }
},
messages: {tFieldRef: “*”}
});
});
}
function validateForm()
{
????????????????? how EXECUTE VALIDATION FORM
}
createValidation()
datos basicos:
Referencia:
——————————————————-
The objective is:
a) Create the validators when page is load.
b) Have a button in order to execute the validation and depending of the result do one action or another.
I don’t know if the explanation is clear enought .
Thanks for your help.
@Oscar: Sorry, I need some more to understand your problem. It seems like something got lost from your comment. Could you try to upload an example page somewhere? Or send a mail? Whatever works for you.
Jorn,
validation plugin docs present an example to use errorClass attribute. I’m using this simple script to show error messages in red colour:
.errormsg {
FONT-WEIGHT: bold; COLOR: #b80000
}
And jQuery:
$(“#frm”).validate({
event: “keydown”,
errorClass: “errormsg”,
but when plugin validates my form and display error message in black colour. What’s wrong? It’s possible to insert style inside validate plugin?
Cheers
is it possible for the messages to be graphics instead of text? so instead of a message saying “invalid email” it can be a check-mark graphic next to it?
You already thought about validating a input file? Only allowing some extensions.
Only an idea.
@Marco: That is a bug in the plugin. Until I release the fix, you could just use the default “error” class, eg:
@andrew: I saw some forms on the internet that use just that, and thought about how to implement support. Haven’t come up with anything yet, any ideas are welcome.
@Leonardo: That could be achieved with a custom method, something like this:
I guess you can’t avoid passing around some regular expressions.
i toyed around with using css to place a background image and positioning to have it over a graphic of an accepted icon, that way with it is correct the error graphic would disappear and leave the correct one showing.. the only problem was that it would only appear if there was text in the error field in the javascript config section and it would only be as long and tall as the text itself.. i would imagine if you can make the error a html image tag instead of a text string that would work out a lot better.
the following is not correct code but to give an idea..
instead of a text string:
email: “Please enter a valid email address”
make it a html image tag:
email: “<img …”
@andrew: That sounds like an easy solution. Did you try that out? The error-label creation uses the html() method to set the content of the label, so it should already accept HTML messages.
i havn’t done too much testing with it yet, but i do know that i cant simply put the image code into the config section..
messages: {
email: CODE
}
i was hoping for an easy way to do it without modifying your code if possible..
i got it to work.. it does something weird though.. the first key down it shows the graphic but on the second and all following it shows the actual image code as a text string and not the graphic itself..
great plugin Jörn. I’m moving all future projects to this. No crap in my html! yes!
Is there a collection of rules extensions around yet?
Thanks for all the work.
Will
@andrew: Ok, I know how to fix that. Need to use html() instead of text() when updating the generated label.
@will: So far I’ve got nothing organized, but plans to do so. I’d start by just putting every additional method I get back into one file, so you can pick what you need. The problem so far: I got a few methods, but no documentation or examples, so its nearly easier to write the method yourself instead of figuring out what it actually does.
thanks.. works perfectly now.. just a thought though, i dont think it would hurt anything to make it html by default would it? that way you can advertise the default function of using graphics as indicators..
Hi, excellent plugin, thank you very much.
I’ve spent the last three hours tearing my hair out trying to figure out why my very simple form would work in FF2 but not in IE6… I tried everything and finally had to break it down line by line and discovered that it was my content type for the page. It was originally utf8 now it’s “text/html; charset=ISO-8859-1″ and now it works perfectly. Thought that this might save someone some time.
Best, Mark.
Thanks for the comment, Mark.
Indeed, there were reports about problems with IE6 while FF worked fine. Maybe it was the same issue.
Hi,
Great work.
Just a question: it seems to me that addErrors function doesn’t exist. Am i wrong?
Phil
I am also seeing the UTF-8 vs. ISO-8859-1 error in IE6.
The problem appears to be that the url regex on line 923 fails when the content type is set to UTF-8:
url: function(value, element) {
return !jQuery.validator.methods.required(value, element) || /^(https?|ftp):\/\/[A-Z0-9](\.?[A-Z0-9ÄÜÖ][A-Z0-9_\-ÄÜÖ]*)*(\/([A-Z0-9ÄÜÖ][A-Z0-9_\-\.ÄÜÖ]*)?)*(\?([A-Z0-9ÄÜÖ][A-Z0-9_\-\.%\+=&ÄÜÖ]*)?)?$/i.test(value);
},
Removing the characters ÄÜÖ “solves” the problem; or, setting the content type to ISO-8859-1 also “solves” the problem.
Perhaps someone with more knowledge of IE/JS/regex/encodings can explain?
Great plugin, btw — thanks for it.
Perhaps I’m doing something wrong, but I would like to validate input fields onChange rather than onBlur. But whenever I use
event: changeI get an error “change is undefined”.Forget it, I realized I wasn’t passing the event as a string. So, instead of :
event: changeI should have be doing:
event: 'change'Lack of sleep…
@phil: As replied on the mailing list, use showErrors() directly.
@Greg: Thanks for investigating this. I guess the trouble is this: jquery.validate.js is encoded as ISO-8859-1. The browser uses the encoding of the page if it isn’t specified for the script.
So a workaround specifies the encoding of the script by setting the charset (eg. <script type=”text/javascript” src=”jquery.validate.js” charset=”ISO-8859-1″></script>.
It shouldn’t be a big problem to encode the source file in UTF-8, that should prevent the problem.
I have a form I wish to reset using resetForm() from the Form plugin. I find that I can get the actual form fields to reset, but the error messages do not. How do I reset the error messages without reloading the page?
@skube: Try this:
Depending on the state of the validation you can skip the call to prepareForm().
Please let me know if that works for you. I'd then document those methods.
It basically works, in that the error labels get hidden, but the input fields themselves are still outlined (in my case red) indicating an error with each field.
Well, I guess its not hard to work around that, too. But I that deserves a better solution, I’ll look into it.
Update: I’ve released beta 2, it includes a new validator method resetForm(). That should do exactly what you need, you don’t even need to call the form plugin’s resetForm().
[...] The validation plugin beta 2 is out! If you are already working with it: A update is recommended. If not, and you need client-side validation (pure or mixed with AJAX requests), check it out. [...]
Hi, Jorn…
I’ve been working with your previous verison of the Validation plug-in and it’s nice to see the updates. (Although, at this point I’m not sure what they all mean…
)
I’m interested in being able to use client-side validation via your plug-in, but also want to be able to use server-side validation with ColdFusion for extended application.
I notice in your AJAX example, that you use a .php file for the back-end (server-side?) code. Would I be able to use a ColdFusion file (.cfm) in the same manner as you use the .php file?
Thanks,
Rick
@Rick: For that to work your cfm has to return JSON in the same format as in the example, that should be no problem.
thanks for you code,
but I a request. In form i fill the error data the validate will show error message. how did you add a method to show pass message when i fill the true info…thanks
@huangminghu: Could you provide some more details about what you’d like to achieve? Maybe post a demo page?
Here’s a situation for you problem solvers out there:
I am using the form plugin to submit my contact form and update an element on contact.php with the response. The validation plugin keeps the form from being submitted while errors are present.
It works as expected in Firefox and Internet Explorer when contact.php is viewed directly. Validation catches errors until the form is submitted correctly; and the heading of contact.php changes from “Contact Us” to “Thanks for your message” on success.
However, when I use jQuery’s load() to put contact.php in a div on another page, validate() and ajaxSubmit() no longer work in Internet Explorer. The window redirects to the form’s action page (form.php) and displays the success message there.
Has anyone tried something like this or have any advice? Thanks in advance!
Does contact.php contain the JavaScript to setup validaiton and form submit?
I guess the key is to seperate those scripts from the markup, or rather from the pages you use. So basically you’d either show contact.php directly and execute those scripts on DOM ready, or you include that page later and execute those scripts after the markup is loaded.
I’m just wondering if there is a way to only validate those forms which are currently shown. I have a page which has several forms most of them hidden until the user clicks a button to display any one particular form. At that point, I wish to validate only that one showing form. Perhaps something like $(“form:visible”).validate({ … }) which doesn’t seem to work…
@skube: Could you detail that some more? Do you hide actual form elements or only parts of a form?
If you have more then one form element or can change your structure to use them, you shouldn’t have any problem at all.
If you hide only parts of one big form it is a bit less trivial. One possible approach would be to modify all required-rules to apply only when the surrounding “subform” is visible.
If that doesn’t help you: Please provide a test page for me to look at.
I can’t really put together a test page right now, but I have emailed you a link to the dev site. I have several separate forms dynamically generated but all individually hidden. They are all separate forms, each with a unique form ID. If the user opts to fill one out, it gets displayed and validation show occur.
How would you intercept the validation with a regular button
instead of a submit button.
The plugin seems to have a hook on the onsubmit event.
@Eddie: Take a look at the form-plugin-integration example. The way the showErrors() method is called to display other messages would be the same as hijacking the validation itself. You can call form() and element() directly to trigger validation of the entire form or a single element (which you have to pass to element()).
This should get you on the right track:
Please let me know if that works or not. In one case it may be possible to find a more elegant solution, in the other we should be able to find a different approach that actually solves your problem.
As always, a test page can work wonders.
First off, love the plugin and the doc. I am having a simliar issue with hidden values. I have one form, however parts of the form are hidden until something occurs, like a radio or select box. I am having a problem figuring out a way to validate only if visable. I have parent divs which will hide or show sections based a select dropdown.
I would try a dependecy required if I could figure out how to make it dependent on a specific select value.
I have also tried adding the {required:true} class to the elements when they are shown, however adding the class after the validator is initialized doesnt seem to work.
Any input would be appreciated and thanks for the great work!
@Jason: If you can decide when to validate based on the visibilty of some parent element, you can use that like this:
I’d need to see the actual markup to tell you which expression would be the best choice. Maybe using the XPath-parent expression like “../div:visible” would work.
Otherwise you can still use a function to determine the dependency, that is much more flexible, but shouldn’t be used in combination with metadata. Use the plugin option instead in that case.
@Jorn, should have thought of {required: “div#parent:visible”}. It worked great since I have 5 main hidden sections which are taken care of by other functions, so this dependency works very well. Quick and easy, thanks for the fast response. You guys should spin up a forum.
Plugin could generate one label when the field is validated. It has this option and I do not know?
I want to show an image (checked) when the field is validated.
Any idea?
@Jason: Great to hear you got it all working.
@Leonardo: It is possible to define HTML as error messages. Check the docs for the “messages”-option and take a look at the second form on the first demo page.
I’ll try to add an example that shows how to do that, but it may take a while.
Let me know about your progress. As always, test or demo pages help a lot.
Hi,
I don’t know if me previous message was clear enough. So, let me try to explain again.
What I want to do is the following: when the user type something in a input and it passes the validation, so I want to show a check image in the side of the input. If the input text does not passes the validation, so show the error message (I’m already doing that).
Something like that: http://www.rememberthemilk.com/signup/
Is this possible?
@Leonardo: No, not yet.
Awesome Work! I couldn’t find your email address, so… I thought I would just post this here.
Again, awesome work! I have a use case, where… I allow the user to pop up multiple Form windows. And there was one minor bug, where the default error label was being applied to the first window. Validation was working properly. Anyway, I modified lines 588 and 589 to reference only children of the current form.
this.settings.errorPlacement
? this.settings.errorPlacement(error, jQuery(“#” +this.currentForm.id +” #” + id) )
: error.insertAfter(“#” +this.currentForm.id +” #” + id);
I hope that is right. Great Job. And I’m using your TreeView control as well. Awesome Work. Thank You!
Jimmy G
Thanks Jimmy. I had a different change in mind that would fix that problem, too. I’m gonna change the internals to carry around the element reference so I don’t need that ID at all.
Hi Jorn
Excellent script and thanks, i dont know what i have done wrong but in IE7 it is coming up with the following error
line:159,155,
Char:1
Error: Object expected
code:0
but in FF everything is working fine with no errors?
Link to page
http://studay.co.uk/test/342/orderform/sampleform.htm
Cheers
@Stu: Can’t see anything wrong with that code. Try to take parts out and see if you can find the source of the problem.
Hi Jorn, I’m looking for a client-side replacement for the ASP.NET validation library. We already use jQuery everywhere, so a plugin like yours would be ideal.
Is there a way that you can specify an arbitrary element to be shown and hidden as the error label for an input field with a validation rule?
We just want to toggle the visibility of elements that contain the error message for a given input field. Each element would have an ID.
I couldn’t find a way of doing this just from reading the documentation.
thanks
@Sam: From what you write I’d say you need to use the showErrors option to customize the message display.
Hi Jörn,
I’m using your plugin for the first time today, and I’m getting an error in Firebug when using one of your examples:
missing } after property list
[Break on this error] rules: {\n
It doesn’t seem to be missing from the example, but it breaks the page.
Here is the example:
$(“#myform”).validate({
event: “keyup”
rules: {
firstname: { required: true },
age: {
required: “#firstname:blank”,
number: true,
minValue: 3
},
password: {
required: function() {
return $(“#age”).val()
@Adam: There is a missing comma after the event property.
Ji Jorn,
First of all, I would like to congratulate you for this great plugin! I have one concern as it was stated by you saying that “Error containers with errorwrappers are not perfect yet in IE6.”. I wonder what was that limitation to your plugin ? Can you please elaborate more ? Thanks in advance.
cheers!
Hi, great plugin, thank you for the work. Had a quick question though. If I have a main page which then loads a form through an ajax call, how can I rebind the event listener? Basically if the form is loaded through an ajax call, the $(‘#myform’).validate(); call does not appear to work. I have tried to use both ‘bind’ and ‘load’ to re-hook the listeners that appear to be broken and have tried to call the validate function from the form tag onSubmit call but nothing seems to work. Sorry for the beginners question, bit new to the javascript and jquery world although I’m enjoying it. Thanks again for the great plugin
regards,
Andreas
@Roland: Open the container demo in IE6 and click Submit in the second form. There is too much space between the error list items, most likely a CSS layout issue, but I couldn’t solve it yet.
@Andreas: It should suffice to call the validate plugin after the form was inserted into the page. Something like this:
[...] Eins davon ist das Plugin Validation, mit dem Forms clientseitig sehr einfach validiert werden können. [...]
Great code, the only thing i noticed is if theres a comma separated validation. ex. required: 3 keywords required, use commas to separate.
Is it possible?
@Jimmy: I don’t get your question. Can you explain it some more or give a more detailed example?
Hi,
I get the following error when trying to run the plugin with Mozilla v1.7. Any ideas what the problem may be? I’m worried some of my users may be using this version of Mozilla. Thanks!!
Andreas
Error: unterminated character class
Source File: http://localhost/gssl/js/validate/jquery.validate.js
Line: 1009, Column: 64
Source Code:
return !jQuery.validator.methods.required(value, element) || /^\d{4}[/-]\d{1,2}[/-]\d{1,2}$/.test(value);
@Andreas: Can you please check if the problem persists with the latest revision?
[...] El plugin de bassistance.de fue la solución mas fácil de utilizar. [...]
[...] jQuery Form Validation [...]
The validation doesnt execute? Basically i want the validation to execute if ‘Type Event Title … && ”’ is presence show validation, otherwise dont validate… but its not working. Help please
ex. SCRIPT
tbtitle: {
required: function() {
return $(“tbtitle”).val() == ‘Type Event Title …’;
}
ex.HTML
@Jimmy: You should start by checking all selectors, eg. $(“tbtitle”) seems to be wrong.
Jorn,
First of all, great job on the plugin. I am using your latest pluggin (beta 2). I have a situation where I want to trigger validation based on someone changing a select menu or submitting the form. The validation is working great when I submit it. However, when I chabnge teh select menu, the validation method seems to get invoked, but always retruns true, even though I have not entered data for some required fields. No errors are getting reported in my error container and my call to $(“#avicapture_form”).validate().form() always returns to true. What am I doing wrong? Any help would be appreciated
Here is the code for the change for my select menu:
here is the validation code. Note the event I am using to triggerr the validation normally is on Submit:
Hi Jörn,
I think my case need to be described in scenario.
1) I have a template, say
<input type=”text” name=”foo” class=”{required:true}” />2) I need to append this string into my table and eventually it is successfully appended.
Now, the thing is your validator seems to be unable to pick up this dynamically added . Is that one of your limitation ?
I have tried using the following code
but no luck…
it works fine if that input is not generated during run time. Any idea why or how should I write it ? thanks for the great plugin again.
@John: Could you please post a link to a complete example? I’m sure it can be solved, but its very difficult with those two fragments.
Until then, here is a bit code that you should try out:
The submit event is always applied to the selected form, while the event specified via the option is applied to each element. And you should work with a single validator instance, though I’m planning a change that allows you to do that without saving the reference.
@Roland: Generated inputs are something that I haven’t considered yet. Thanks for bringing it up. I need to give that a shot first, but it should be easy to add a hook that allows you to refresh the elements to validate. Currently those are selected only once, just reapplying the validate method won’t help.
This worked out great. I really appreciate it.
There was one side effect of the validation. I also have a submitHandler (that I omitted in my first eaxmple, but included in this one) in my “var validator = $(“#avicapture_form”).validate({…”. One of the side effect of forcing the validation by invoking the “validator.form();” is that the form is also getting submitted. Is there a way to supress that when I am just validating as opposed to a legitimate Submit (Clicking on a Save button with type “submit”) ? Esssentially, I don’t want to submit the form when the user change the “select” menu, just validate. Again, thanks a lot for all your help. Here is the example:
$(function() {
// validate form on change and submit
var validator = $(“#avicapture_form”).validate({
rules: {
//Schedule 1
START_DATE0: {
// required: function() { return $(“#SCHEDULE_STATUS01″).is(“:checked”);},
//required: function() { return $(“input[@name='SCHEDULE_STATUS0']:checked”).val() == 1 ? true: false;},
required: function() { return $(“#SCHEDULE_STATUS01″).is(“:checked”) ? true: false;},
date: true
},
submitHandler: function(){
// submit the form
submitAviForm();
}
});
$(‘#SCHEDULE’).change(function() {
validator.form();
$(“#SCHEDULE”).val() == 0 ? $(“#schedule_0″).show() : $(“#schedule_0″).hide();
$(“#SCHEDULE”).val() == 1 ? $(“#schedule_1″).show() : $(“#schedule_1″).hide();
});
});
Sorry for the barrage of questions, but I also noticed after I sent my message that the validator.form() isALWYS returning form even though the form has no errors and is actually submitting. Since what I want to do is stop the select from hiding the current screen and showing another, this is causing an undesirable effect.
$(’#SCHEDULE’).change(function() {
// This is ALWAYS being returned as FALSE regardless whether
// the page has errors or not.
if (validator.form())
{
$(”#SCHEDULE”).val() == 0 ? $(”#schedule_0″).show() : $(”#schedule_0″).hide();
$(”#SCHEDULE”).val() == 1 ? $(”#schedule_1″).show() : $(”#schedule_1″).hide();
}
});
});
Hi Jörn,
Thanks for your reply. Could you send me an email for notification once you got that hook done ? or you have to wait until for your next release to have that feature of refreshing the element for validation ?
Desperately need that feature
I would say this is the last stage for me to get through the testing in order to confirm whether to use your plugin or not.
cheers man!
@John and Roland: I’ve fixed it. Please give beta 3 a try and let me know if it works for you.
@Roland: Check the custom methods example and validator.refresh(). Documentation isn’t perfect up-to-date yet, but I’ll work on that for 1.0 final.
[...] As usual, all interesting stuff like downloads, examples and documentation are on the plugin page. I’ve also updated the Plugins API browser if you prefer that form of documentation. [...]
Hi Jörn,
I had downloaded your beta 3 and apply the changes. It works! Thanks a million and once again, great plugin!
At last I can finalized to use your plugin in our project. It is indeed a good support from you as well. Maybe you would want to have a donate column in your page.
I downloaded your Beta 3 and tried it. It now works great. The implicit call to validate the form no longer results in the form being submitted and the validate returns true or false, depending on whether I have errors on the page or not. Thanks a lot for all your help.
Great plugin and support. I really appreciate it.
Hello again. I noticed another strange behavior when using the range value (rangeValue) validator. If I specify a value between 0 and 999 (rangeValue: [0, 999]) and I enter an invalid value (i.e 2000), I receive the following error:
Please enter a value between and 999
Note the “0″ is MISSING after the “between”.
However, if I specify a range between 1 and 999 ((rangeValue: [1, 999]) ) and enter an invalid value (i.e 2000), I receive the following error:
Please enter a value between 1 and 999
Note that the “1″ DOES appear after the between.
Am I doing anything wrong here?
Here is my validator function. As usual thanks for all your help.
$(function() {
// validate form on change and submit
var validator = $(“#tracking_form”).validate({
event: “submit”,
rules: {
// Background
UPDATE_FREQ: {
required: true,
rangeValue: [0, 999] // This cause the 0 not to show up in the message
}
});
});
@John: No, that is a bug. I tend to use the default operator quite often, and that causes issues when a value of zero is valid. Thanks for reporting, I’m glad someone uses the plugins and helps improving it.
I’ve fixed the issue, and commited it to jQuery’s subversion repository. Normally you can get it directly from there, but currently the svn browser isn’t available. Therefore I’ve updated the release package, please just download it again and give it a try.
Thanks a lot. That fixed the problem. Everything is working well now. Again, great and very useful plug-in and support
I would like to show only “*” for all validate rules, are there any way to set “*” as default message for all validations?
Resubmit?
I have a form with a submit button.
I have next code:
jQuery(‘#seccionesForm’).submit(function()
{
var options = {
//target: ”,
beforeSubmit: preSubmitSeccion, // pre-submit callback
success: postSubmitSeccion // post-submit callback
// timeout: 3000
};
test = jQuery(“#seccionesForm”).validate(
{
submitHandler: function(form)
{
jQuery(“#seccionesForm”).ajaxSubmit(options);
return false;
}
});
Submit button call a asp page to save all fields.
Then:
First click on submit button : work nice.
Second click on submit button: send the form twice
3 click: send form 3 times…
Any idea why is send more than one time?
Thanks!!! This is a great pluggin!
Hi,
I’m still getting the following errors on a fresh install of Mozilla v1.7:
Error: invalid quantifier {
Source File: http://localhost/gssl/js/validate/metadata.js
Line: 95, Column: 13
Source Code:
if ( !/^{/.test( data ) )
Error: unterminated character class
Source File: http://localhost/gssl/js/validate/jquery.validate.js
Line: 1031, Column: 64
Source Code:
return !jQuery.validator.methods.required(value, element) || /^\d{4}[/-]\d{1,2}[/-]\d{1,2}$/.test(value);
Any ideas?
Thank you kindly,
Andreas Sandberg
Hi Jorn,
Regarding the post above, I was able to remove the functions that caused the problems, one validated the ISO date which I didn’t need, and the other did a regular expression test for test data in metadata. Everything works fine now, but I wonder what Mozilla didn’t like. Thanks.
Andreas
Hello,
What do you do if you have some javascript you must run that requires an input parameter after clicking a submit button. For example, I have two buttons to submit on the page, one labeled “Save” and one labeled “Next”. Depending on which button is clicked I use javascript to set a hidden variable with the value “Save” or “Next” that is given as a parameter to the javascript function. Unfortunately, if I use the onclick event to call this function when the submit button is pressed, validation no longer occurs. How do I get around this problem?
@John: Cool
@Oscar: You could try to overwrite all default messages with this:
Regarding your second question: Why do you assign the validation on each submit? The call to the validate plugin itself adds a submit event handler.
@Andreas: Oh well, looks like I’ve got to install Mozilla 1.7. I’ll let you know if I find something.
@Dean: You could try to handle that via a different submit handler. Something like this:
That should run your own submit event handler before the validation handler. Using event.target should give you the information you need.
Thanks for the reply. However, I am still not sure how that would give me access to the information about what button was pressed.
event.target gives me the name of my form and the other attributes of the event object don’t give me the name or the value of the button on the screen that was pressed.
Hi,
I found that in Bate3 there is a place using $() explicitly, assuming that there should be no conflict naming.
489 reset: function( element ) {
490 this.errorList = {};
491 this.toShow = $( [] );
492 this.toHide = $( [] );
493 },
I had not tested this but I think it would cause some problems when jQuery() is used instead of $().
Hi!
I have a quick question.
Instead of a submit button (
@Li: You are right. I’ll remove that as soon as possible. Thanks for spotting.
@L. Cosio: Seems like your message got screwed by the html filter. Can you please try to post it again or send it to me via email? Thanks.
Thanks Jörn for your reply .
Msg Issue: Great!
Resubmit:
I am not sure to undestand your solution.
If I only have:
var options = {
//target: ‘’,
beforeSubmit: preSubmitSeccion, // pre-submit callback
success: postSubmitSeccion // post-submit callback
// timeout: 3000
};
test = jQuery(”#seccionesForm”).validate(
{
submitHandler: function(form)
{
jQuery(”#seccionesForm”).ajaxSubmit(options);
return false;
}
});
The validation is not executed, after press submit button is executed the action of the form.
Sorry if my explanation is not very good.
@Oscar: I can’t see anything wrong with the code you posted. It would be much easier to help you if you could provide a demo page. If your code is part of a larger application, extract the interesting part to a single html file.
Hi Jorn,
Awesome plug-in thanks!
One problem: My forms are hidden when the page loads – the onLoad handler doesn’t seem to attach the validator to the form. Works fin for visible forms. Is there a way to correct this or do I have to attch the validator only once the forms have been shown?
Hello,
How can I change the validation rules on my form ?
I have to set the request:true for a field only if the user clicks on a radio button (without reloading the page). I’ve tried with the validator.refresh() but the validator remains the same.
Thanks in advantage
Ste
@Julian: “Hidden” like display: none is set somewhere in the stylesheet? That shouldn’t cause any problems, but I haven’t tried that myself. I’ll let you know if I find something.
@Ste: You meant “required: true”, right? In that case you can use the depedency checking. Replace “true” with a string or a function like this:
I recommend to use the first approach, providing a jQuery-expression. If the expression returns at least one element, the field is required.
The plugin also provides “:blank” and “:filled” to use within those expression, allowing you to make a field required when another field is empty or has some content.
Thanks for your patient seem that finally works… however I have another issue….
My page have two forms.
I validate the first but I cannot validte the second.
First one have rules:
jquery(“DB”).validate(
{
rules: validations,
submitHandler: function(form)
{
jquery(“#DB”).ajaxsubmit(options)
}
}
In options I have a postSubmit Action that execute the validation of the second form:
function postSubmit()
{
.
.
jquery(“sectionForm”).validate(
{
submitHandler: function(form)
{
jquery(“#sectionForm”).ajaxsubmit()
}
}
}
I don’t know why the second validation is not executed. In the second form the validations are done using meta: class={required:true}
Any suggestion?
Thanks
[...] Marketo.com (The comapny I work for as UX Architect) is launching their flagship product and public site this week. Uses a bunch of jQuery, Tabs Plugin, Validation Plugin and Scrolling Promo Effect. Design was done by Sean Zimmerman. HTML Production was done by NetKitchen and myself. Overall, I think it’s a solid looking site. [...]
@Oscar: The call to validate() doesn’t execute the validation immediately. For that, you need to call the form() method of the validator object, in your case it should be ok to do it like this:
Hi Jorn!!!
You are the best!
Now works fine…. let me another question…:-P
Are there any way to use another “tag” instead of “class”?
ex:
I need use:
@Oscar: That example didn’t quite come through, but it sounds like you want to use a simple feature of the metadata plugin.
You can find an example in the custom methods demo, the interesting line is this:
Allowing you to specify validation rules via metadata with test=”required:true”.
Hi Jörn,
Great plugin! Got it working without too much trouble and it works perfectly. One quick question. Has anyone asked about phone number validation? I couldn’t find anything documented anywhere on validating numbers will characters that would normally be found in a phone number like (,),or -. Any suggestions or pointers?
Thanks
Al
@Al: So far there isn’t support for phone numbers yet. In any case you can add additional methods using jQuery.validator.addMethod(), details are documented in the API.
For phone numbers I see a few possible approaches: One that only validates allowed characters. One that validates the exact format. Or one the simply disallows entering invalid characters, maybe even in a given format. The latter can be achieved without any trouble with the masked input plugin, which I can highly recommendate.
[...] As always, all interesting stuff is on the plugin page, with more API documentation in the Plugins API browser. [...]
Hello! Your validation plugin is an excellent extension to jQuery’s already-formidable library. I’m quite pleased with it so far.
However, I’ve noticed that Release Candidate 1 no longer validates textareas for me–neither in IE nor Firefox. Not even the example you provide with the download validates the required textarea.
Also, when I tried using the packed version with IE 6, I got an error “Expected ‘:’”. Using the unpacked version gives no error.
Hi Jörn,
Validation can validate elements when a form is submitted. But in some browsers, like Firefox, using a password manager, a dialog will be shown for changing or remembering password when password input element is contained in the form being submitted. It’s annoying when there are errors in user’s input because Validation will stop submitting to show invalid input after the dialog of the password manager. Can you allow Validation to watch specific event, such as the click on submit button, which is triggered before submitting, to validate the form. If that, invalid input will be pointed out and the submit will be stopped and no dialog from password manager. The dialog only appears when there is no error in user’s input.
Hi Jorn,
I want to be able to customize the error messages upon form submit. For example, for a particular field my error message should be –
“Please fill in an appropriate” + phoneNum + “number”.
the phoneNum variable could be either “mobile”, “office phone”, “residence” based on a drop down value.
So, the question is can I redefine some messages on form submit based on some form field value selected/filled by the user?
Please let me know.
I have one html who call one iframe with ajax content via thinkbox
The link in ths html is that:
My problem is when i click in this link all the iframe is loaded but when it finish i get this error in ff
$.validator has no properties
So i click out of the thinkbox and it close, withount reload the page i press again in the link, and now the content appear
If i test the script alone it work perfect, but not calling the thickbox
Any1 have an idea why i getting this error?
Thanks in advance
The enviarmail.php script show the next html (only a part, the rest maybe could be the example and still dosnt work)
$(document).ready(function() {
$.validator.setDefaults({
debug: true
});
$().ready(function() {
var v = $(“#enviarmail_form”).validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
dataType: “json”,
after: function(result) {
if(result.status) {
v.showErrors(result.data);
v.focusInvalid();
}
}
});
}
});
});
jQuery(“#reset”).click(function() {
v.resetForm();
});
});
Correo/s electrónico/s
***********
***********
Jörn,
Thanks for the suggestion. I went ahead and wrote a method for phone numbers and thought I would reply with it in case someone else has need of something like this. It’s a simple validation that checks to see that the correct number of numbers were entered. I’m sure someone can think of another way of doing this but for just US phone numbers this seems to work fine.
@Ben: Thanks for reporting, I’ll fix that.
@Li: I haven’t noticed that behaviour yet, thanks for reporting. As it is a bit difficult to replicate: You say its enough to stop the click-event to prevent the password manager to popup on invalid forms?
@Mandy: You could add a change-event to your select and overwrite the message you configured. Something like this:
While the options object that you pass to the validate-plugin is copied, its elements can still be referenced and changed.
Please let me know if that works for you, maybe there is an easier approach.
@sebastien: I can’t see any obvious issue in your approach. Could you post a testpage?
@Al: Thanks for posting, could be indeed quite helpful for others. I’ll try to gather someone additional validations that you can pick from. Of course it would help a lot if you could provide a bit documentation and one or two examples what the method does, that is, what is a valid phonenumber.
ok, lets try w/o thickox, i get the same error
in this url u can check this, and if u could helpme thx a lot
http://www.belarsoluciones.com.ar/test/
[...] It uses the Masked Input Plugin. I like this plugin alot and used to do something similar with my inlineError form. However, I think I will switch to this new method. It’s much stronger. I tried to use the Validation plugin, but I just couldn’t get it to behave how I wanted. The plugin author assures me that it is possible and might collaborate with me to come up with some more varied demos. I am excited to contribute. [...]
Hi Jörn,
Can I call a javascript function JUST right before the form is submitted ? Meaning that right after all of the validation has passed through the rules and no errors and therefore the form is ready to submit. So, just right at that moment I would want to call a javascript function. Is that possible ?
cheers!
Hi Jörn,
One more question. Is it possible for me to trigger your method $(“#form”)validate() at the later stage(just right before submit) instead of during $(document).ready(); ? This is because some of the field(input) will only be assigned with the rules(class=”required:true”) at the later stage instead of the first load of the page.
cheers !
Hi Jörn,
Yeah, I have already tried using refresh() method but it seems to still submit the form without validating the field.
Initially, the field looks like the following :-
after some logic from my end, i’ve assigned the attribute validation to the class and it becomes…
Then I tried to do a refresh() and submit the form, somehow it won’t validate that field but instead submit the form directly. What happen ?
@sebastien: You are trying to access the validator object before it is loaded. Moving the call the $.validator.setDefaults into the document.ready block could help. Otherwise you have to wait for the script being fully loaded by using the $.getScript-callback.
@Roland: Your examples didn’t quite come through. Can you post an example page or email them to me?
Hi Jörn, thx for your reply, now i fix the problem loading direct the script, but i made some change look what happend when i call via thickbox.
http://www.belarsoluciones.com.ar/test/
Howdy, Jörn. Thank you for this plugin; it’s already saved me a great deal of time!
I’m not sure if this is a bug or a feature—it seems the former—but when I have a rule like:
quantity: { required: false, digits: true }
…then apparently no check is done to make sure that the value of “quantity” actually matches “digits”. (In other words, the field is allowed to be blank or any value.) However, when specified as:
quantity: { digits: true }
…I observe the correct behavior: the field is allowed to be blank or just digits.
Any thoughts? I can email you an example if this doesn’t sound like what you expect to happen so that you can see it in context. If it is what you expect, perhaps a clarifying note could be added in the documentation.
Hi Jörn,
I love the validator, but, I’m having an issue with the error boxes. When a field is valid they are marked as hidden rather than removed, and when they come back, the have style=”block” in the label. This is OK if your label is always a block, but alas mine should be inline…
Any hints? Ideas?
@sebastian: I couldn’t find any obvious errors in your code. I’ll let you know if I find something.
@Steven: Thanks for reporting. This is a bug: The parameter to required is ignored, it doesn’t matter if you specify true or false. I’ll try to fix it or at least better document it.
@Dave: It should suffice to set display: inline explicitly in your stylesheet for the error labels. I had to do that in the errror-container demo to get the display right in IE6. Let me know if that works for you.
Hello.
Love the plug-in – thanks!
Can you help me with a behavior issue. I find that when I tab to a field controlled by the validator, the error message is fired before the user has a chance to enter a value. Is this correct? Have I set it up badly?
Thanks!
@Chis: I’m working on that behaviour, improving it to be less obtrusive. This is the current plan:
– improve general validation behaviour, set these defaults and make them configurable:
– validate invalid elements on keypress, removing the error as soon as possible
– don’t validate valid elements on keypress/focus, giving the user the chance to enter the correct value before complaining
– validate elements on blur but make required optional. if required would pass, check other rules
– validate everything on submit
Hey Jorn,
For some reason, the validation plugin will only validate form elements when the ID and name attributes on the element are identical. This appears to be the problem with the textarea problem I mentioned before–my textarea had a different name from its ID, whereas all the other elements had identical names and IDs.
Okay, now I feel like an idiot. ^_^
I just read your “recent changes” and saw that it works on name now. :r My apologies–it’s late. Please feel free to delete these comments.
I should probably stop coding for tonight…
Then Ben we should use id or name into validations rules?
Hi Jörn,
I just downloaded your updated RC1 version of the validator. I’m having a problem with the errorClass though. When there is an error on my form, the errorClass gets applied to the entire form. So, for my error messages, I have set the text to be red when invalid, now the entire form has red text.
Any ideas? It was working fine in the Beta 3 version.
Nice plug-in. Thanks.
Thanks for the plugin! Although I’m not a JavaScript expert, and it took a bit of time to grasp how it works, it seems about as easy as possible, given it’s vast extendability.
Here are just some additional rules that work like minLength and minValue, etc. rules:
Follow up to my previous post; it looks like the check function was modified in the RC1 version to also set the class of the element’s parent to the errorClass.
Is there anyway to just set the errorClass for the element and the error message?
Thanks.
@Ben and Oscar: The rule of thumb is this: Name attributes are required, without them validation doesn’t work. IDs are optional, if provided, they are used in the for-attribute of the error label.
@Jose: Thanks for reporting. When adding that I assumed that each input field is wrapped by another element and not a direct child of the form element. I wonder if it would work to simply filter out form elements:
looking at your examples now, I see what you mean. I think I’ll need to wrap my inputs in their own elements. I have another case where I have a div containing text and an input field. In that case also, the text preceding the input field is changed when there is an error in the input field since the containing div has its class set to the errorClass.
Thanks.
@Jose: I see. In that case it seems like the better approach to simply adjust those CSS selectors to style only the error labels and input elements.
[...] Validation by Jörn Zaefferer – This is a tricky one. It doesn’t exactly work the way I want, but Jorn has been extremely nice and asking about form suggestions. I am hoping the next version will address some of the issues I had with it. [...]
Hi Jörn,
Great software. I have been playing with several of your plugins for a day now am very impressed with the quality. I have a functionality question. I am using your Tooltips with the Validation. For example, in my form I have elements each of which has a label and a text element. Immediately after the text element I have a link which I am using as a Tooltip anchor. As follows:
?
My issue is that the Validation system inserts its error label between the text field and the Tooltip anchor. This is, of course, the expected result. Is there a way that I can get the error label added after the Tooltip anchor?
Thank you for your time and generosity,
Mike
Hi Again,
Sorry about the previous post. Guess I do not know how to transmit the HTML in this comment submission system. I simply included some HTML fragments in line. I also had a typo in my email address. The above is now correct.
Mike
On the Demo Test page:
http://jquery.bassistance.de/validate/demo-test/
on the “Validating a complete form” form, clicking in the Firstname (or Lastname, Username or Password) field, entering nothing and then tabbing to the next field causes an error to be displayed next to and for the second field. More tabbing results in the correct behavior though. Problem appears in FF, Safari, and Opera.
Any suggestions?
Hi Jörn,
Looking at your radio button & checkbox example, if there is an error with the checkboxes, the first checkbox in the group is being hidden. It looks like it has the same class set as the error label, but since the error class has a ‘display: none;’, the first checkbox containing the validation rules is being hidden.
any suggestions on getting around that problem?
Thanks again.
This is an excellent validation plugin, thanks!
I’m having trouble with one set of behavior. Is there any way to require a text field if a checkbox is not checked? The opposite of the scenario in the examples section where you have:
required: "#newsletter:checked"How might you go about something like this:
required: "#newsletter:unchecked"?Hi Jörn,
Thanks for the great plugin. I have a problem though i was hoping you could help me out with. My script works perfectly in IE 7 but not in firefox 2, talk about weird. I know its something to do with the submitHandler function, am i using it correctly? Please help….sample code is below:
—————————–
————————————-
cheers,
Hagen
@Mike: You can customize the error placement using the errorPlacement option. In your case something like this should work, assuming that each field has such an anchor:
The default error placement uses
label.insertAfter( element );.@Erin: I’m working on that behaviour. I’ve already got the keyup and blur behaviour improved alot and they are active by default. Stay tuned!
@Jose: Thanks for reporting. That is a bit ugly, I’ll fix that as soon as possible.
@Elliot: There isn’t an expression yet for “unchecked”. The plugin already provides “:blank” and “:filled”, so adding “:unchecked” seems like a good idea to me.
@Hagen: I can’t see anything wrong in your script. Could you provide an example page?
I’m having some trouble with a dynamic table in a form that I validate. I can add rows to the table (the text inputs are required), and do a validate.refresh(). This works fine.
Now, if I remove the dynamically added rows and they would have failed validation, the form will not submit. If, however, I remove the dynamically added rows and they would have passed validation, the form submits just fine.
I’ve tried adding a validate.refresh() on my remove (like I have on the add), and it doesn’t seem to matter.
Thanks in advance for your help.
Hi Jörn,
I have an input field where I would like to allow comma separated numbers and decimal values but only if they’re positive.
Using something like:
myField: {number:true, minValue: 0}
I get a validation error in minValue if I enter a number like 3,500
Is there any combination of the existing methods that would support this number?
Thanks.
The error messages say “then”, when they should say “than”.
@John: Sounds like a case I haven’t taken into account yet. I need to investigate where the problem occurs. An example page would help alot.
@Jose: Someone asked for this before, I’ll try to add something.
@Brandon: Thanks, I’ll fix that.
Jörn,
Once again, thanks for the great pluggn.
I’ve written a few extra methods I thought people might appreciate. This brings your jQuery validation up to where our prototype validation was previously:
In addition I found an easy way to provide a required if unchecked method:
Is there a way to perform validation on two events? I’d like to validate my form both on “keyup” and “blur”, but “event” only accepts a string — not a map of events. Any way around this?
Cheers.
@Ermath: I’m working on much more interactive validation. You can preview it from svn or wait for the RC2 release. I’m designing it to give the user feedback as early as possible, without ever disturbing him. And you won’t have to configure anything.
Thanks for making such a great tool to aid in client side validation. I ran into an issue today… and I don’t know if it’s something I’m doing wrong or a bug, but in the contact form I created, if the last input in a fieldset fails validation, every label in that fieldset turns red to indicate an error.
To see this, go to http://www.visionalechoes.com/contact.php
The first 3 inputs are in a fieldset, with the phone number not being required… just type a letter in it to make it fail. And the description is in its own fieldset so when it fails, its label changes too. If the last element in the fieldset passes but another fails, this doesn’t happen.
Any suggestions?
vEchoes: There is definitely going something wrong. For a first check, could you trie the latest revision? Odds are good that the problem is fixed there. Please let me know if that helps or the problem persists. In the latter case, it would help a lot if you could extract a test page (just the markup and scripts). Thanks.
Thanks for the quick reply. I extracted the form and scripts and only included the styles necessary to illustrate the problem.
Also, I tried the new revision and it didn’t fix the problem. As a matter of fact, it’s now running the validation process onBlur on some of the text elements… sort of running amok. and the label colors are still changing colors.
Extracted form: http://www.visionalechoes.com/contact2.html
Okay, I’ve removed the feature that adds the error-class to the field’s parent element. There are too many issues with it. Please give the revision from svn another try.
Hi Jörn,
Thanks for this neat validation plugin. I have some problems though i was hoping you could help me out with.
I have this code:
– HTML
1
2
...
– JavaScript
$('#form').validate({
tickets: {
required: true,
number: true
}
});
first problem is related to validation above-mentioned select element on IE (exactly on line #556) – it’s always invalid.
here goes the second: in new version you refactored showErrors method, therefore there’s no way of using it without corresponding element(s) (i wanna be able to use it as generic error handler, but there are number of situations where i cannot pass corresponding error element). could you maybe make some “public” method which can be used to display errors with or without elements attached to them (taking Array of Strings/Objects as an argument for example) ?
Thanks in advance.
Hello Jörn,
I am using thickbox to load a page containing a login form through ajax. I am then using the validate plugin. Everything works fine in FF but IE just submits the form to the target page without triggering any validation. The login form works perfectly in IE outside of the thickbox. If you could point me the right direction that would be much appreciated. I read the comments left by Sebastien and your responses but havent been able to arrive at a solution.
Thanks,
Josh
[...] Its out! A version of the jQuery validation plugin that I call 1.0 final. [...]
Hello Jörn,
This is really a great plugin!!!!
For all those who get problems whis thickbox, try using thickbox with iframes, it work for me with FF and IE.
Hi Jörn,
Great plugin!
I just tested version 1.0 final and I encounter one problem with “keyup” event. With my code and version 1.0 final it’s not working. When I use version 1.0 beta 3 “keyup” event works just fine.
Best regards,
Sławek
PS. You can even delete submitHandler section. “keyup” event still not working with ver1.0 final and works with ver1.0 beta 3.
@Slawek: That is a regression I could have avoided. I already have some much more advanced code ready to handle keyup and blur events in a more appropiate way, but that didn’t make it into 1.0. Unfortuanetely I forgot to put the old event-code back in.
I’ll try to release 1.1 soon. It just needs some more testing.
I just installed the 1.0 final and all my blur events quit working.
On RC 1: event: “blur” works fine.
1.0 final: event: “blue” doesn’t do anything.
Is there another way to do blur now, or is this a regression?
Thanks
Sorry, didn’t see your most recent message before I posted mine.
Hi Joern
Thanks for this wonderful plugin.
I have a question regarding the display of error messages though:
Each of my input elements is surrounded by a label element. The error message should be a strong-Element that is prepended to the label content. This works fine using the errorElement and errorPlacement option. But I would like to highlight the entire label if there was a validation error. I tried to use the errorPlacement function and added an additional class to the label parent of the element.
To get rid of this additional class I use the success function:
success: function(errorStrong) {
errorStrong.parent(‘label’).removeClass(‘error’);
}
But this way the class is not added again if the errorStrong element is reused, e.g when doing multiple checks on one element.
When I now remove the errorStrong element in the function success the adding and removing of the css works fine but there is a bit of flickering when one error message is replaced by another. Do you have any tips on how to improve this?
Thanks
Claudia
@John: No problem, I should have avoided that regression in the first place.
@Claudia: My previous solution to this was adding the error class to the fields parent element. Unfortuanteley that caused way too much trouble, so I simply removed due to lack of a better solution.
Another idea was this: (Optionally) find the label-element for an element (element-id must match for attribute, doesn’t have errorClass) and toggle its errorClass.
The flaw is obvious: How to identify error-label and element-label once the error class is added?
Maybe a simple callback that is called for adding and removing the error class would be the best solution in this case.
http://jquery.bassistance.de/validate/demo-test/custom-methods-demo.html does not work for me in either Firefox2 or IE6. I get “validator.errorList has no properties” line 38 in firebug
Just looking at this plugin for the fist time. A dent to confidence when the example pages do not work
@alek: Yeah, thats a bit ugly. I’ve noticed it meanwhile, it should be fixed in 1.1 which should be released pretty soon. Please let me know if anything else is not working.
Also linked on the demo-page is the testsuite, more then 300 tests (and counting) running against the plugin. It isn’t complete yet, but I’m working on it.
Great plug-in, thanks for your work on this!
I have an issue, and I’m not sure where to turn. I an error in firebug when I load my page. It seems to keep the plug-in from working. Anyone have this issue?
Error:
Window schedule has no name assigned (line 569)
URL:
http://admissionstest.unl.edu/daily_visit/schedule/?type=High%20School%20Senior
If this isn’t the correct place to post this question, please provide an alternate.
Thanks!
@Seth: I don’t get any errors on that page. For an active community check out the jQuery discussion list.
The script “jquery.validate.pack.js” from the 1.0 final version is NOT working with IE 6.
“jquery.validate.min.js” & the unpacked version works OK.
Somebody with the same problem?
And also the page http://jquery.bassistance.de/validate/demo-test/ doesn`t work in IE6 (IE 6.0.2900.2180.xpsp_sp2_rtm). No error thrown, just submits the forms.
Hi Jörn
Thanks for that great plugin.
It is somehow possible to disable validating after setting it or overwrite settings? I got an form in which some elements are shown but can be switched to hidden. Of course when they are hidden they should not be required.
I tried to just overwrite the settings but it didn’t work out.
Thanks,
Michael
@Sebastian: Sorry for including the packed version without testing it. Should be fixed soon.
@Radu: I’ll check that, thanks for reporting.
@Michael: That sounds like you should use the dependency-checking supported by required. Check the examples in the API-browser for jQuery.validator.method.required.
Yeahhh, best plugin ever
Found an solution:
elementwhichishidden: {
required: function() {
return ($(‘#parentelement’).css(‘display’) != ‘none’);
},
minLength: 3
},
[...] Hooray! Version 1.1 of the validation plugin brings, along a few bufixes, sophisticated validation on blur, keyup and click events. They are designed to help the user where appropiate, without interrupting when he hadn’t even the chance to enter anything. [...]
@Michael: There are two even shorter solutions, one being much shorter, the other more flexible:
Thanks Jörn, implemented it that way.
I got an other question. I got one select-field in my form which should throw an alert when it is incorrect. How can i do this?
Hello, Jörn. This is an extremely minor thing, but you might want to go through and do a search for “no longer then” and replace it with “no longer than”. It’s part of one of the validation error messages and is not quite grammatical. It shows up at least once in the documentation (and here on the website) and then once in the code.
Thanks (again) for the fantastic plugin!
-Steve
@Michael: You can apply validation rules to selects as normal. To display an alert you have to use the showErrors-option.
@Steven: I think I fixed all those buggers now. Its an annoying mistake I keep repeating…
The only thing I can say is: YEAH!. That’s a huge, great pice of coding art you’ve done here!
Greatings from Toruń, Poland!
Hi Jörn. Glad you put the blur and keyup events back in. I tried v1.1 (even the latest from svn), but I’m having trouble with keyup. When I first navigate to a field, keyup does not work. Then if I TAB out of the field and Shift-TAB back to it, keyup works perfectly. Any idea to what causes this?
Keep up the good work!
I found it quite annoying when the keyup validation starts before I had the chance to enter anything. The users and designers I talked to agreed with that. “Fixing” that by tabbing shouldn’t work either. Currently tabbing “fixes” it only when you enter something (incorrect), and then tab forth and back. Keyup validation gets activated when an error message was already displayed.
Does that make any sense? In case you need to provide keyup validation without exceptions: How about an option to enable that? Would that work for you?
Strangely i have tried on another XP machine and things seem to work just fine. Works ok with 6.0.2900.2180.xpsp_sp2_gdr. As soon as i have acces to the machine i have got the first report, i’ll retry.
PS: Thanks for the great job!
Jörn, good point — I see what you mean. In most cases you would indeed want to wait with keyup validation. In my situation, the user has to enter some rather specific and longish entries, and we want to guide the user along the way by displaying various icons while he/she is typing away in each field. So an option to enable it would be great (default off).
Hi Jorn,
I’m wanting to insert a password strong validation in our users form. Microsoft haves a great example:
http://www.microsoft.com/protect/yourself/password/checker.mspx
This example uses an external js for validation. How can I “plug” this routine in a form(already) with your Form Validation plug-in? Cheers
@Radu: Oh well, weird IE again.
@Ermath: Okay, I’ll add that then. Default: default. True – immediate validation. False – no keyup validation. Sounds like a plan, doesn’t it?
@Marco: The checker routine and result display is a whole plugin itself, but it gets really interesting in combination with validation, eg. a at least strong password is required.
Implementing the basic stuff is more work that I can currently spend on any jQuery related development. If you take up the task or find someone (eg. on the jQuery discussion group) to do it, I’d be happy to integrate it into the validation plugin.
Is it possible disable the message for one input in the form? There is no space left for the message, but when i don’t define a message, the standard message is displayed.
Thanks,
Michael
@Michael: The current workaround is to specify whitespace as the message.
username: " ". I’ll try to fix that.Jorn,
I am getting onblur validation even though I am not specifying it. I only want validation on submit. What could be causing this? I just moved our code from version 1.0 beta 1 of the validtion plugin to the latest 1.1 version from the subversion repository. Below is the code to use the validation plugin in our pages:
$.meta.setType( “attr”, “validate” );
$( document ).ready( function() {
var options = { focusInvalid : true };
$( “#MyForm” ).validate( options );
} );
Thanks,
Mark
Hi Jorn,
There still seem to be issues with the blur, keyup stuff in 1.1. I can’t get it to consistently work on any of my sites, so I went and played with your example here:
http://jquery.bassistance.de/validate/demo-test/custom-methods-demo.html
It’s pretty easy to break it. In particular, that first textarea that is required and needs 3 to 15 characters. If you click around and enter various numbers of characters eventually it will either stick on and will never be ok, or it will never come on and it just stops reporting an error.
For me the last version that works consistently with respect to blue is RC 1.
Thanks
John
Great plugin, has anyone used an AJAX callback to validate a form field? I have something like this but i’m not really sure how to handle the async aspect of this
Any suggestions welcome
jQuery.validator.addMethod(“uniqueUsername”, function(value) {
$.get(“${ctx}/members/usernameValidator”, { q: value }, function(msg) {
if(msg != “”) {
// do something cool here
}
});
return true;
}, “${rb(‘register.error.username.unavailable’)}”);
Thanks again for the plugin
Evan
@Mark: Those are now default since 1.1. You could always go back to 1.0 (all releases on jquery.com/plugins.
I have been lazy on documenting those options in detail, sorry about that. To disable onblur-validation, specify onblur: false as an option. Same goes for onkeyup and onchange (which is actualy onclick).
@John: In RC 1 only the do-validation-always-on-this-event option was available. I guess there was no way to break, but it wasn’t very usable either. I’m having an idea on how to reenable the always-validate-on-whatever without too much trouble when someone needs it. Nonetheless I’d like to get the more sophisticated system working. I appreciate your help with this: How exactly can I reproduce the issue you are having?
@Evan: AJAX validation is something I want to get into the 1.2 release. I have some stable stuff working (demo). There is a new “remote” method which accepts an URL, and some additional stuff in the submit-handler to prevent a form submit while requests are still pending. It looks like it is exactly what you need. If you want to give it a try, you can download the latest package. Your feedback is appreciated.
Hi Jorn,
Here’s a simple html page that I can reproduce the inconsistency in:
Fails in both firefox 2.0.0.4 and IE 7.0.5xxx
Test for jQuery validate() plugin
$().ready(function() {
$(“#commentForm”).validate({
event: “blur”
});
});
A simple comment form with submit validation and default messages
Name (required)
E-Mail (required)
To reproduce the problem:
1. Load page.
2. Type characters in the name field.
3. Click into E-Mail and type characters
4. Click back into name and delete all the characters
Fails here – Name doesn’t validate the required:true.
Take 2:
Test for jQuery validate() plugin
$().ready(function() {
$(“#commentForm”).validate({
event: “blur”
});
});
A simple comment form with submit validation and default messages
Name (required)
E-Mail (required)
Sorry, the html won’t show up here, but you can grab it with view source.
I don’t have an external site readily available to put this on for you to see it easily.
Thanks
something wrong is with this plugin when ia have in input class=”{validate:{required:true,number:true}}”
and in js
var container = $(‘div.container’);
$(“#forma”).validate({
event: “submit”,
errorContainer: container,
errorLabelContainer: $(“ol”, container),
wrapper: ‘li’,
meta: “validate”
});
required option works good only on submit but number onblur shows me messagebox with all errors not only for this input
Congratulations for your work. Its realy a good job.
And thanks for shared…..
kakaroto
agencia de web
@Thanks John, I’ll take a look.
@Tomek: The required-rule is ignored for empty elements on blur. That way you can tab through elements without getting annoyed by error messages. I see that there are scenarios where you want to have the validation occur nonetheless for required, I’ll add that option in 1.2.
Hi,
Just implemented your validation plugin, it works great for my needs ( had a bit of a problem getting it to validate an tiny mce editor field, but worked around that now ).
But I have one major problem, have one form and 3 submit buttons, each with a separate id/name. On the server side I use php and in a switch statement perform different actions depending upon which submit button is pressed.
The problem I’m having with the validation plugin is that 2 of the the submit buttons only require the page id and version id to validate (and is not concerned about the rest of the validation ), but the plugin is trying to validate all the other fields.
Is it possible get the plugin to validate certain fields depending upon which submit button was pressed?
here is the code for the validation:
var container = $jQuery(‘div.form_error_container’);
// validate the form when it is submitted
$jQuery(“#commentForm”).validate({
focusInvalid: false,
errorContainer: container,
errorLabelContainer: $jQuery(“ol”, container),
wrapper: ‘li’,
meta: “validate”
});
Thanks in advance
Mark
Thanks for the link to 1.2 (pre-release) I have added it to our development code and it seems to work well in both firefox and safari though I have not had time to test it on IE.
Great work, I look forward to 1.2 final
Evan
@Mark: You can use both expressions and callbacks for the required-method to specify dependencies. Though keeping track of which button was clicked is a bit tricky. I don’t have a solution at hand. It may be worth taking a look at the form plugin, specifically its ajaxForm method.
Thanks for the quick reply.
Will have a play with JQuery trying to catch which button was pressed and store that in a global var and maybe use to to check again?
Thank again
Mark
@Mark: Yeah, something like that. A bit off my head that may help you:
Hi Jörn,
On your test page there is example with ErrorContainer option used. I have two questions regarding this:
1. Is there any way to hide ErrorContainer box when all errors are corrected?
2. Is there any way to validate form with ErrorCointainer only after hiting submit button? (I’ve delete event option and is still update the ErrorContainer div)
Many thanks in advance!
Slawek
Very nice!
Works great in FirFox 1.5 & 2
But it does not work in IE7. The form submit anyway without checking anything … like in the exemples you provides. Is there a trick to make it work?
Thanks
Hi Jörn,
I did a few changes in the code (v1.1) to make it work with arrays in Struts, as well as remove the error container when all the errors are corrected (also in the demo here: http://jquery.bassistance.de/validate/demo-test/errorcontainer-demo.html). Probably same as Slawek’s 1st question?
Added ‘ around id or name in errorsFor() to allow ‘[' and ']‘ in element name / id:
return this.errors().filter("[@for='" + this.idOrName(element) + "']");
This should be done in showErrors() as well:
element: jQuery("[@name='" + name + "']:first", this.currentForm)[0]
This is what I did to remove the error container:
// Return the number of visible error labels in the label container.
// Probably need more checks so it won't break for inline error labels
visibleErrors: function() {
if(this.labelContainer) {
return jQuery(this.settings.wrapper + ':visible', this.labelContainer[0]).length;
}
return 0;
}
And added this to the end of hideErrors():
if( !this.visibleErrors() ) {
this.containers.hide();
}
@Stef: The plugin is supposed to work in IE7. Could you be more specific? Are the demos not working or only your own setup? If so, posting a test page would help alot.
@Gregers: Great patches, thanks. I’ve added the quotes and I’ll give the other proposal a try.
Hi Jorn, I have a new question.
Are there any way to validate the format number¿?
I have a field that should be a number but I would like avoit that the user uses . (like separator) are there any solution?
@oscar: Does the digit-method help?
Hi Jörn,
Any feedback about ErrorContainer option?
Best regards, slawek
[...] Of course the alternative to building your own framework is to use an existing one. This approach yields some important advantages, amonst them the “given enough eyeballs, all bugs are shallow” principle. [...]
I use multiple elements with the same name (… type=”text” name=”someElemAsArray[]” id=”someElemAsArray_1″ value=”"….) to obtain arrays in the backend. How am i able to obtain validation for all those elements and not just one? As i see , this prevents me from doing it:
// select only the first element for each name, and only those with rules specified
if ( this.name in validator.rulesCache || !validator.rules(this).length )
return false;
Any way to obtain validation on (all of) these kind of fields?
Hi Jörn,
I’m still trying the errorContainer option and I figure out, that if I have some value that indicates any error in a form than I could use it to hide errorConatiner when all errors are correct. I was look for such value into even source code, but can’t find anything useful.
Another approach is to trigger some one value during validation process.
Any feedback would be great.
Best regards,
Sławek
Very useful plug-in and I had no need to ask any questions because most of them were answered in the comments. Thanks again for this.
Hi Jörn,
I am trying out your validation plug-in and, although I am still learning it and what it can do, I think that it is a great plug-in.
I do have two questions.
(1) Is there a way to specify that some validations only take place when the form is submitted? I am validating the form as information is begin entered–the behavior that I want. However, I have some additional validations that I only want to perform when the form is submitted (they refer to the relationships of multiple inputs); making these validations during form entry would be annoying to the user. I have two cases:
(A) If a checkbox is checked, then a text field must contain a value and, if the text field has a value, then the checkbox must be checked.
(B) I have four text fields. If any of the first three fields have data, then all of the first three fields must have data. The fourth field is not required, but if it has data, then the other three must have data.
(2) If I write my own additional validation in the submit handler, can I access the error messages for the fields that I find in error at form submit time?
Thank you for your help.
Larry
@Slawek: Thanks for your feedback. I’ll add a invalidHandler-callback (I’m still looking for a good name) in 1.2: It’s called each time a form is submitted and invalid. That should solve a lot of those problems. Though the errorContainer-behaviour needs some tweaking in general. So far that feature seemed to be hardly used, so your further feedback will help a lot.
@Radu: No, currently all names have to be unique for a group of fields.
@Bios: Glad to hear that
@Larry: From your descriptions it sounds like you can handle those requirements by specifying dependencies for any required-rules. That won’t necessarily defer validation until submit, but could work in most cases.
To access error messages: The plugin doesn’t save references to those, instead uses jQuery to search them. Currently the submitHandler is called with just one argument, so for accessing validator-methods for searching those labels you have to save a reference to the validator object that is returned by the plugin method. I’ll work on that to make it easer.
The interesting method is
errorsFor(Element): Just pass in an element and you get back a jQuery object containing the error message for that element.Let me know if this helps you.
Hi Jörn,
Many thanks for that info Jörn!
If plugin already search for any errors in the form, than you can only add some if element. You already develop errorContainer value which manage the visible value of the errorContainer element. So, the simple if command should do the magic: if no error is found in form disable errorContainer element (which must be defined in validation function).
Maybe some extra value will be required. For example. Before validate form some value is always set to for example to ’1′. Then all fields in form will be validate and if any error will be found this value should have ’0′ value. Then at the end of validating function should be if statement. If value=1 hide errorConatainer else show errorContainer.
Best regards,
Sławek
Hello. I came across the need to validate only part of a form, that is, the form elements which were currently visible on a tabbed page. I come up with this, based on validator.prototype.form():
jQuery.validator.prototype.validatePartialForm = function(parentstr) {
this.prepareForm();
var oks = $(parentstr).find(“input, select, textarea, button”); //modified line
for ( var i = 0, element; element = this.elements[i]; i++ ) {
if (oks.index(element) != -1) { //modified line
this.check(element);
}
}
jQuery.extend(this.submitted, this.errorMap);
return this.valid();
}
use it like validator.validatePartialForm(‘#container1′)
@Slawek: I don’t quite get your explanations/examples. Though basically it sounds like most of it is already possible, with just a small modification.
@CBWhiz: That is an interesting approach. I’ll try to integrate the principle into the plugin. Thanks!
Yes, but I can’t figure out where to put it
in jquery structure.
Still looking for the best place inside your plugin.
I’ll give some feedback when I found the place.
Maybe you can point me (nr of lines in source code) where is function which handle errorContainer visible value.
Best regards,
Sławek
@Slawek: That is handled in different places. That makes it rather difficult to spot. The interesting line is in
prepareForm():this.toHide = this.errors().push( this.containers );toHide.hide()is then called inhideErrors().Hi,
realy nice plugin, but i need help:
i have a form with 2 columns with some input fields. By default, the second column is hidden an can switch to visible.
The input fields are only to validate if this second column is visible, but it doesnt work:
If I submit the form with the hidden second column the validate fires for the second column (with hidden input fields) too.
How can i ignore hidden input fields (inputfields in parent elements there are hidden)?
Best regards,
FUSiON
I am trying to dynamically add/and remove validation rules to a form. Someone else mentioned it in your comments, if this radio is checked require this field. I saw the .refresh method and your example of adding forms fields to a form then making them required which I thought I could use. I am not having any luck though. Here is my code:
var validator;
$().ready(function() {
var container = $(“#appForm div.errorContainer”);
if($(‘#marital_status_married’).is(“:checked”)) {
$(“#maiden_name”).attr(“disabled”,”");
$(“#maiden_name”).attr(“class”,”{required:true}”);
} else {
$(“#maiden_name”).attr(“disabled”,”disabled”);
$(“#maiden_name”).attr(“class”,”");
}
validator = $(“#appForm”).validate({
errorContainer: container,
errorLabelContainer: $(“ul”, container),
wrapper: ‘li’
});
$(“#maiden_name”).attr(“disabled”,($(‘#marital_status_married’).is(“:checked”))?”":”disabled”);
$(‘#marital_status_married’).bind(“click”, function(){
$(“#maiden_name”).attr(“disabled”,”");
$(“#maiden_name”).attr(“class”,”{required:true}”);
validator.refresh;
});
$(‘#marital_status_single’).bind(“click”, function(){
$(“#maiden_name”).attr(“disabled”,”disabled”);
$(“#maiden_name”).attr(“class”,”");
validator.refresh();
});
});
Hi,
The info on the char set would better be included in the main information. It really is annoyiçng that these documents do not work properly with UTF char set.
You should note that the document are ISO char sets, and that you should convert them to UTF-8, , which not always produces the correct results.
Thx, A.
I solved my problem myself:
// check function that returns true or false in relation of the class state
function chkknd2(){
return $(‘.kunde2′).css(“display”) != ‘none’;
}
//here the input field and its metadata for this solution
@Fusion: Currently you can achieve that using by specifying required-rules with dependencies. Take a look at the docs for the required method, there are a few examples.
I’m planning to add an option that allows you to validate only parts of your form with less trouble then specifying dependencies for each element.
@Matt: Same here. Refresh is only useful when you add and remove elements from your form. For anything else, using dependencies (look for the required method in the docs).
@Astuanax: I’m not sure about this one. There were a few encoding issues, but jquery.validate.js should be all UTF-8 encoded.
Thanks for the quick response Jorn.
required method worked great!!! I really appreciate it.
here is another one to take shot at. I have the dependent validation setup. When “Yes” is checked the text field becomes required. Say a user has clicked “Yes” then tried to submit. They get the error saying to fill out the text field. They realize they meant to click “No”. So on the click event for that radio set I would like to recheck the form.
I can do that with validator.form(); where validator is my validation object. What I want to avoid though is calling form() before the form has been submitted once. Is there a way to set some sort of variable to know if the form has been, at least attempted to have been submitted?
Hello Jorn,
Thanks for developing and sharing such a nice plugin! However, I am running into some performance issues (notably with IE7 and Safari). The validation does take place as I expect. However, once all fields are valid and the submit button pressed, it takes quite a long time for the response to show up… allowing the user to click the button several times. Is there something wrong with my code? Is there a memory leak somewhere? Unfortunately, I cannot post a link to my development environment.
I appreciate any help you could give.
Thanks Again,
-Gerard
My form is contained in a Thickbox (iframe), I’m using the Form Plugin and your validate version 1.1.
$(document).ready(function(){
$(‘#ContactForm’).validate({
focusInvalid: true,
errorPlacement: function(error, element) { error.appendTo( element.parent(“label”) ); },
errorElement: “span”,
errorClass: “warning”,
rules: {
first_name: “required”,
last_name: “required”,
email: { required: true, email: true },
phone: “required”
},
messages: {
first_name: “Required”,
last_name: “Required”,
email: “Required”,
phone: “Required”
},
submitHandler: function(form) {
$(form).ajaxSubmit({
target: ‘#display’,
success: resizeit
});
}
});
// post-submit callback to Thickbox – resize the iFrame unless Safari
function resizeit() {
if(!$.browser.safari){
self.parent.$(“#TB_window”).animate({height: 200}, 500);
self.parent.$(“#TB_iframeContent”).animate({height: 200}, 500);
}
}
//end doc ready
});
@Matt: You could check if validator.submitted has any entries. Not the perfect solution but could work in your case. I don’t quite get what exactly you want to do, if you could show me an example page I could try to implement a better API for that.
@Gerard: I can’t see anything obviously wrong with that form. So far I haven’t done any performance tuning on the plugin. An example where actual performance problems occur would help a lot.
The problem of test pages is always the same. And in most cases its possible to extract the interesting parts to produce a working example that concentrates on the actual problem. If you are working with a lot of dynamic serverside stuff, just save the page as rendered in the browser and modify it a bit to get the scripts working.
Hi Jorn,
is there a method to show a loading graphic once all content is valid and the submit button pressed? I’d like to give some feedback to the user and prevent multiple submissions.
Thank you for the great plugin.
-G
You could put the necessary code into the submitHandler-callback.
Jorn, could you show me some example code for the submitHandler callback? I want the submit button disabled only if all fields are valid.
Currently, I am doing this with the submitHandler:
submitHandler: function(form) {
$(form).ajaxSubmit({
target: ‘#display’,
success: resizeit
});
}
Thanks for your help.
-G
[...] Currently I’m investigating ways to leverage those plugins on the server-side too, which is especially interesting when considering the validation plugin. John’s work on implementing a browser environment in Rhino is amazing. It already is able to run the full jQuery test suite, and the possibilities for building web application frameworks based on jQuery are daunting. [...]
I will type up what I am trying to do in a day or so. I think you will understand it better with a better explanation.
Is there a way to disable the keyup validation that happens on default?
Hello,
I have a fix for sending array elements to the server.
modified file jquery.validate.js
idOrName: function(element) {
return this.checkable(element) ? element.name.replace(/\[\]/g, “”) : element.id || element.name.replace(/\[\]/g, “”);
}
HTML File:
$().ready(function() {
$(“#Form”).validate({
rules: {
“arrayFieldName[]“: {
required: true,
minLength: 1
}
}
});
});
A
B
C
Please select one or more
so the server get $_REQUEST["arrayFieldName"] as array
Jörn – great work! i am having a problem i cant figure otu though…
i am building a form, and would like validate a group of fields based on if one of them has a value….. like for a address, city, state, zip – making them fill all fields if they have filled any one of those, if they leave all blank, dont error check. I tried
f_address: { required: “#f_city” || “#f_state ” || “#f_zip” },
f_city: { required: function() { “#f_address” || “#f_state ” || “#f_zip” },
f_state: { required: “#f_address” || “#f_city ” || “#f_zip” },
f_zip: {
required: “#f_address” || “#f_city ” || “#f_state”,
digits:true,
maxLength:5
},
no luck. i am new to jscript i dont know if ‘||’ is the ‘or’. what i am trying to say is if any of these have a value, rerquire all. how would i do this? i cant figure it out ~
mike
@Gerard: How about this:
@Matt: You can pass onkeyup: false as a plugin option. Sorry for lack in updates to the docs.
@Guido: Thanks, looks good. I need to check how compatible that really is.
@mike: Those expression have to be valid jQuery selectors. So as long as you aren’t sure if the syntax is correct, just test it on your page. Firebug is very handy for that, just open the Console tab and enter a jQuery selector like $(“f_city”) and you should see what gets selected.
In your case this should work:
f_address: { required: “#f_city:filled, #f_state:filled, #f_zip:filled },If one of those fields is field, the selector returns at least one element, and the field is required.
Note that :filled (and :blank, which selects elements without content, ignoring whitespace) are added my the validation plugin and are not available without it.
Hi,
how can i manual reinitialize the metadata ({required:true}) in the input files if/after i add a new objekt to validate.
bye
fusion
Hi,
i solved the problem with the metadate myself.
Now i have a new Problem:
If i add a new input field with metadata validation tag like ({required:true}) and reinitialize the validator with (validator.refresh), the ‘blur’ validation doesn’t trigger on the new objekt.
validator = $("#addkunde").validate({
event: "blur",
submitHandler: function(form) {
$(form).ajaxSubmit(options);
return false;
}
});
Hi Jorn,
I’m using the validator plug in to populate a UL inside a hidden DIV with the error messages – I then want to display this DIV using jqModal if the form does not validate. How would I execute custom code if the validation rules I have in place fail?
typical. as soon as i post a comment asking for help, i figure it out
for anyone trying to do something similar, here’s the whole setup i used:
Plus any rules and messages. #errors is a DIV containing a H1 and an empty UL element to be populated with errors.
Jörn – Thanks for your help, that worked.
However that trick didnt help me overall, I still need to know if there is a way (and the syntax) to use ‘and’ or ‘or’ (&& or ||) in required statements… is this possible? I would write this in another language as:
if (#f_address:blank && f_city:blank && #f_state:blank && #f_zip:blank && #f_telephone:blank) {
// all fields are empty, we need at least one way to contact them
#f_email: required: true;
}
Anyone have any idea how to include a profanity filter to jquery.validate?
I have all my validations working properly, but I’d like to be able to prevent the user from using words like “test” or any other profanity.
Thanks,
Ben
@mike: You can always use a function to determine whether or not a field is required:
rules: {
f_email: { required: function() {
return $(“#f_address”).val()==”" && $(“#f_city”).val()==”";
}, email: true
}
}
I just need this plugin , try is first and say Thks second
Thanks Steven – I am new to jQuery, so it is taking a little bit to get my head around its syntax, butit seems really great. i appreciate your help.
~mike
the newest 1.1 jquery.validate.pack.js do not work in IE6 SP2, it fire a exception, at line 14 and line 15, jquery.validate.js and jquery.validate.min.js works.
I needed to do partial form validation as my form was split into tabs in the tabs plugin. I created this, calling it onClick when switching forms: (parentstr is the jquery selector for the container of those form elements, eg, #div4)
[code]
jQuery.validator.prototype.validatePartialForm = function(parentstr) {
this.prepareForm();
var oks = $(parentstr).find("input, select, textarea, button"); //modified line
for ( var i = 0, element; element = this.elements[i]; i++ ) {
if (oks.index(element) != -1) { //modified line
this.check(element);
}
}
jQuery.extend(this.submitted, this.errorMap);
return this.valid();
}[/code]
I wanted to use red border to indicate invalid fields, so I had to change in jquery.validate.js, line 558
jQuery(element).add( jQuery(element).parent() ).addClass( this.settings.errorClass );
to
jQuery(element).addClass( this.settings.errorClass );
because otherwise I got borders where I didn’t want them.
Please consider this option for a future versions.
ugh. ignore my previous post, it turns out I was using an old version of the validate plugin
I am having a similar issue as fusion. I am creating objects on the dom after the page/form has already initialized and loaded. I am doing this multiple times and will never know if it will be clicked or how many times. This is becuase I am duplicating sections of a travel form for additional travelers, etc…and will never know what the user wants. Rerunning the validator function each time makes the validation work but does not prevent the form from submitting when errors exist within the newly created dom objects. Is there a better way to validate objects that may or may not exist after the page has been set up (perhaps separate validator instances)? This function runs on document.ready and the other objects are created when the user clicks a button:
Thanks!
i have a form
i trigger the submit using $(‘#frmData’).submit()
now i was wondering if there was a way to not trigger any other effects if the submit still has errors.
The button that triggers the submit also triggers some fade effects that basicly loads the next page. I dont want those te be to performed if there are still errors. But how can i make for example an if statement that checks if there are errors ?
Hi Jorn,
I would like to show warning messages if users enter values outside a given range, yet I want them to be allowed to submit other values even with the warnings.
What do you suggest?
Thank you,
Milano
@Fusion: Thanks for the report. I haven’t considerd that case, but its easy to fix. I need to initialize those event handlers inside the refresh method.
@mike: In that case you could just use plain callback functions, they allow you to use everything that JS provides.
Well, like Steven said.
@douwen: Thanks, I’ll check that.
@CBWiz: Cool, that looks like an interesting approach. I’ll try to find a nice way to integrate that into the plugin, so that it still works with a normal submit.
@Steven: Cool
@Jason: The problem with those event handlers is the same as in Fusion’s case. The other is the problem that you can’t specify additional rules at runtime. That may be a bit less trivial, as long as you can’t just use metadata.
@wolvman: You could start with moving that code into the submitHandler. It is called only when the form is valid.
@Milano: You could try a validation rule a try that always returns true (valid) but uses validators capabilities to display messages when appropiate. You can always do this:
Call that from within a validation method and it could work. If it doesn’t you need to add some extra stuff somewhere to start the validation and then just use showErrors to display the warning.
Let me know if that helps, if we can get that straight I’d like to add it to the plugin.
I have solved my problem by moving the validator to load into a variable at the bottom of the page (cheesy but it works). I then run validator.reset() and then validator.refresh() within each of the functions that is duplicating sections. This seems to have solved the issue of the submit not being prevented.
My major issue was the basic fact that I need to use the validator object but only after the page was set up. That object needed to be stored some place and if you stick it in a ready() then you have to bring jquery along with it and its a big mess.
It would be nice if I could instantiate the object and then have then have a method available for refresh without having to reference the initial object again. That however seems difficult.
Thanks for the great plugin. I am using it many of my corporations forms and this post is just a testament to how complicated it use can get. It works well (though I wish IE performance was a bit better on large forms). Thanks!
Hello,
I copied the demo you have at:
http://jquery.bassistance.de/ajax-validation/demo-test/milk/
I have made no code changes, but I get the following error (from Firefox’s error console, and it performs no checking):
Error: jQuery.validator.methods[rule.method] has no properties. Line 663.
I would greatly appreciate any insight you have as to what the issue is?
Thanks for writing some awesome plugins!
@Jason: Great to hear you got it working. I’d welcome a more detailed example on how exactly your setup now looks like. That would help a lot, either for others with the same issue or for me to provide an easier solution that can be integrated into the plugin.
About performance issues: That is on the todo list, so far I didn’t bother at all with performance tuning, so there should be quite some potential to go for. In the worst case I need to use native DOM methods directly, but with the current testsuite it should be pretty obvious where that works out and where not. I hope I can provide a boost in performance with the 1.2 release.
@Chris: Did you also copy jquery.validate.js from that site? If not, try that, or the latest revision from SVN. That demo won’t work with the 1.1 release.
Hello Jorn,
Thanks for this wondeful work. Very much appreciated. I gave the ajax validation on http://jquery.bassistance.de/ajax-validation/demo-test/milk/ a testdrive but somehow it doesn’t work smoothly in IE6 when the required is set dependent on wether another field is filled. The form is submitted in IE anyway. In firefox it works fine. If I change the required to true than it works fine in both browsers.
so: required: ‘input#zipcode:filled’, doesn’t work
required: true does work
Regards,
Fnoppie
@Fnoppie: Thanks for the report, I’ll check that.
If i try to use any of the validators provided in additional-methods.js FF gives me a JS error “this.depend is not a function”. Can anyone help me with this?
first of all: great work Jörn!
I’m looking forward for the 1.2 release because I need the remote-ajax-check.
I don’t know if it’s already a known bug, but the remote-check in this demo
http://jquery.bassistance.de/ajax-validation/demo-test/milk/
isnt working correctly:
If you input a username that begings with a invalid one (like Peterr) and the onkey-check is active, you just need the right timing to display the error-message for a valid username: “Peterr is already in use”. If you now move the cursor or blur the field it becomes valid again.
You can reproduce the bug as follows:
enter something in the username field
defocus it
delete it (so now the onkey-check is active)
enter “Pete” and then really quickly “rr”, you’ll see that the error message keeps displaying “Peterr is already in use”. Now move the cursor or defocus the field: Peterr is now valid
It would be great if we could specify an animation for the labels. It is already possible to animate them while showing, but for hiding them, it simply disappears. I went through and changed every “hide()” to “fadeOut()”, but it would be better if that was customizable. Perhaps an entire “errorHide” function to be executed whenever the error should be hidden, just like “errorPlacement”.
Walking through the code to get ready for implementation I noticed
non-English words in critical sections. It may be me though:
in “xx.validation.js” : part of the regex (line 1142) is an example:
9](\.?[A-Z0-9ÄÜÖ][A-Z0-9_\-ÄÜÖ]*)*(\/([A-Z0-9ÄÜÖ][A-Z0-9_\-\.ÄÜÖ]*)?)*(\?(
Clearly it is possible to guess the English equivalents but a friendly alert for you and others also.
Similarly there are lines (7 and 9) in the “additional-methods.js” although less critical.
@phpsc: Could you give the latest revision a try?
@Klaus: Thanks for the report! I’ll check that.
@Ian: Yep, great idea. And those animations would be more then just eye-candy: Its easier to see where error appear and less disturbing than having them just popup out of nowhere. I’ll try to find a nice way to make that customizable.
@Bud: Right, that is far from perfect. I’ll try to tune those a bit. Encodings are alwyas a tricky part for me.
I have two submit buttons on a page: Cancel and Submit. I really only want to perform validation when the “Submit” button is clicked. If cancel button is clicked, I want the form to be submitted (but no validation to occur). What is the easiest way to accomplish this?
@denny: Add a class “cancel” to the cancel button. Easy ‘nuf?
Hi,
I am currently using this plugin, which is working great, but when I switch over to another text field, the error rules are run.
For example, I have a email input box, if the email is entered incorrectly, and the user then switches to another input box, e.g. for “age”, the rules are run, and it says that the email was entered incorrectly, is there any way to prevent this.
I only want the rules to be checked when the user clicks “submit”.
I have defined my own method which sends an ajax request to check a db value, and I want this method to be run as few times as possible.
Thanks.
@Asad: You can disable validation onblur and onkeyup by specifying options onblur: false and onkeyup: false. Sorry for not updating the docs for 1.1 on that.
Hi Jörn,
First, I thank you for your previous responses to my questions and once again complement you on such nice software. My new question may just be the result of my own ineptness with your tools.
I am using the validation package with a form that has a file upload element. I am applying just the standard ‘require’ rule to the element to ensure that the user gives me a file before successfully submitting.
The problem is that the validation code does not seem to recognize that a browse selection has been made. The problem occurs if the user does the following sequence. Click the submit button without a browse selection; this shows the ‘require’ error message as expected. The user then browses a selection (the error does not go away after this action) and immediately clicks the submit button again. Now the error message finally goes away but the form does not submit. A second click of the submit then actually submits.
I think that the validation code is simply not getting an event when the browse action occurs.
I would appreciate any enlightenment on my ignorance.
Thanks,
Mike
@Mike: That sounds a bit weird. Odds are good that its related to the file input. I have to reread on the topic, but basically (some) browsers restrict access to the value of a fileinput. I’ll look into that.
[repost; this time, html-encoded]
This is a very useful plugin, thank you.
Is there any way to change where errorClass is applied? There’s no parameter, as I understand the code, but perhaps you know of a jQuery trick I can use?
Here’s an example to show what I mean. The <div>, <p>, <input> nesting is necessary for other reasons, so we should assume that I cannot do without it.
The HTML:
<div><p><input id="password" type="password" name="password" /></p></div>
..would become the following when it fails validation:
<div><p><input id="password" class="error" type="password" name="password" /></p></div>
..but it would be immensely useful to have the class applied to the grandparent div instead:
<div class="error"><p><input id="password" type="password" name="password" /></p></div>
Any suggestions welcomed!
Followup:
One way to accomplish this is by searching for each statement that adds/removes "this.settings.errorClass", then appending ".parent(‘p’).parent(‘div’)" to the element.
For example:
jQuery(element).addClass(this.settings.errorClass);
becomes:
jQuery(element).parent(‘p’).parent(‘div’).addClass(this.settings.errorClass);
Obviously this is specific only to my implementation, and isn’t a viable long term solution. Sorry, my JS isn’t quite so skilled to be able to make this more generic yet.
We have several jQuery plug-ins that have an image after the input part of the control that the user clicks on to perform some action. For example a calendar edit plug-in has a calendar image after it for the user to click on to display the calendar. Many of these images are placed using the jQuery after() method. Some of these plug-ins we wrote and some are by other authors. When the validation executes and the error message is displayed, the message is displayed between the input part of the control and the image forcing the image to display below the input and the error message in the page. Although everything works as expected, it does not look very good. Is there a generic way for me to detemine, using the validation plug-in, if the control being validated has an associated image after it and to display the error message after the image instead of after the input part of the control?
@Dave: That is really difficult to solve generic without great complexity. I had some code similar to yours that just added the error class to the parent, but that caused a lot of problems where unwanted. I’ll try to find a better solution.
@Mark: Please give the errorPlacement-callback a try. Its called for each error-message-element. If not specified, the plugin just does label.insertAfter(element). Something like this should do the trick:
Thanks, Jörn. The easy stopgap measure is to modify the code directly and hope that the .parent() relationship exists everywhere it’s used… a fair assumption in this case.
If I’m able to find an elegant solution (and the time to do so), I’ll let you know.
Cheers
Hi Jörn,
The plugin has been working great for me. I tried using the “remote” method to validate whether an email address already exists in our system. I am also using ajaxSubmit in the submit handler. However, it seems that sometimes the form gets submitted even when an email exists. In that situation, I get the success message I defined as well as the remote error message.
I have a feeling the form is not waiting for the server response before submitting but I’m not sure what to do to fix it. I noticed when you first mentioned the new remote method you mentioned “some additional stuff in the submit-handler to prevent a form submit while requests are still pending.” Are these in place or do I need to do something in the submitHandler in order to get this functioning?
Any help is greatly appreciated.
Thanks,
Anthony
Hi Jörn, I’m having a few issues with your plugin. I’m validating a large number of elements (60) via metadata and when you go to the page firefox gives the option to abort the script as its find it to be “unresponsive”.
If I add this line of code:
$.meta.setType(“attr”, “class”);
then the error doesnt occur, but the validation plugin stops working :/ so really it could be the metadata plugin or validation.
Was wondering if you could shed any light on this.
thanks
Hi, this plugin is working fine, its great
Im trying to use a list in my form, with options 1,2,3,4,5, and after this choice will appear 1 to 5 forms
I would like to know how can i do this ?
I try with adding this to the javascript, doing the same way thats nezsletter topics in the example
var nbcred = $(“#nbcred”);
var form1 = $(“#form1″)[nbcred.minValue("1") ? "show" : "hide"]();
nbcred.change(function() {
form1[this.minValue("1") ? "show" : "hide"] ();
});
And in the html :
0
1
2
3
4
5
Email
Im only trying with one form for the moment, but it doesnt work…
I think im not using well the minVallue…
thanks
Hi, Jörn.
Congratulation for plugin. I have used this plugin in all my projects.
I bug that i see now is when i have a form with element’s name in array format and a wait validate it. When occurs errors, only the first element’s error of array is showed, because on plugin is verified only the element’s name and don’t the id.
Is there a demo with validation and tabs plugin working together?
[Follow up to my earlier post]
Jorn I tried using the latest “additional-methods.js” from the svn as you suggested. First of all there’s an error on line 10, you have missed opening bracket “(“. I fixed that myself. But it now gives me error “this.optional is not a functional” if try use any validator from it. I am using all default setting and giving the validator names in class as in the first form of your example page. Can you include the “additional-methods.js” in your examples and use a validator from it ?
I was prepare demo with tabs-form-validation on one page.
http://www.netix.sk/forms/test.html
It works perfect in Firefox, but in IE does not work.
Hi,
I am having a bit of an issue with validation.
I have two drop down lists, selecting the first populates the second using Ajax.
Initially the validation works, but when the second drop down is populated the validation breaks.
Any suggestions to get around this?
Thanks.
Hi Jörn,
when using the browser search function to search within this page, your footer “Best viewed with both eyes open!” is always covering up the search results, as the browser scrolls down just to the last line. So actually this page would be viewed best without the “best viewed” bar
Eyes all open,
Bernd
Hi Jörn,
when changing your demo-test/index.html to use your example of
$(“input”).validate({
event: “blur”,
success: “error”
});
the form isn’t validated on blur. I expected the form to be validated when an input element is losing focus, which it doesn’t.
Am I doing something wrong here?
Thanks,
Bernd
I tried the additional method named ‘alphanumeric’, and it doesn’t seem to be working. The following is the code in my form:
alpha
I added the script, , but it still doesn’t work.
Any help is appreciated.
This is a great plugin.
phpsc said, “Can you include the “additional-methods.js” in your examples and use a validator from it ?”
I would appreciate an example like this as well.
Are there plans to add this to the ‘core’ code in jquery?
I wold like to know why jQuery validation plugin doesn’t run in IE when is used jQuery 1.1.3. IE generate “Object doesn’t support this property or method” error
great plugin, thanks so much!
Hi,
I’m having some issues with Radio buttons and the display of the error.
Here is the HTML:
Yes
Yes
No
No
Any Ideas?
http://paulihrig.com/SolutionsApplicantAssignment/default.cfm
OK – first post.
the insert validation works just fine, in all browsers.
but the Update Validation on a 2nd form does not seem to work in IE 6
every thing is great in FF and Safari
it should flag fields that are null/blank on submit..
have been cluncking around with the example code all day..
thanks!
-paul
why would a hidden field cause it to crap out?
ok. got around it after masking the id in a url var.
but shouldn’t this work for field type=hidden
input name=”id” type=”hidden” value=”#INTID#” class=”{required:false}”
i tried the example where you name all your errors & define the required validation, but couldn’t get it to work..
Hi,
Just downloaded your plugin and had a play with it. Have to say I’m very impressed! Excellent work and many thanks! I’ll have to include this on all my forms from now on… It even validates ok!
Thanks,
Tom
The latest SVN version does not pack well.
Jorn,
I’ve run into an issue while trying to use your plugin. I wonder if you can advise me on how you’d tackle it.
I want to submit a form with the usual jquery meta-validation … but, i want to also protect against double submits on the client side.
So, the way I usually do this is: on click of the submit button, only IF the form is 100% valid!, then just before it submits I want to change the text of the submit button to ‘please wait …’ and disable it.
‘only IF the form is 100% valid!’ tells me i’d like to use the SubmitHandler for this but the form in question is not an Ajax form, so i’d have to manually submit the form. Doing so currently causes major recursion/memory errors in IE, FF and Safari… though besides that, everything seems to work. Any suggestions?
Great plugin! I was just wondering why the demonstration page does not accept plus-addressing. Like . These are valid e-mailaddresses and I think RFC 2822 describes this .
@Dave: Yeah, I hoped so too, and immediately got a report where that broke everything.
@Anthony: The remote-validation isn’t stable yet, therefore no official release. I think I’ve now found an elegant solution for the synchronization issues you experienced. I hope to get 1.2 released soon. Once it works there is nothing you should have to do apart from specifying rules and your submitHandler as usual.
@Alli: I haven’t yet optimized the plugin for large forms, but plan to do so. 100 inputs in a single form aren’t that uncommon. To avoid the metadata-parsing-overhead you could specify rules as plugin options, though I guess that makes it harder to generate them on the serverside.
@fwdi: You are mixing validation methods with usual jQuery code. That won’t work. Please refer to docs.jquery.com for documentation about jQuery.
@Estevão: Array elements will be supported in 1.2!
Could you post a test page for your IE problem?
@Miro: Thanks for the test page. I’ll try to set something up that works also in IE.
@Asad: Can you provide a test page for that? Would help a lot!
@Bernd: I’ll remove the, you are right, its really annoying.
The blur-validation doesn’t work that way. Currently the element is always validated on blur, though not when it doesn’t contain anything yet. I’ll improve that in 1.2 so that you can explicitly configure to always validate on blur.
@Tom: I’ll work on tests and documentation for those additional methods.
@Dave: Your HTML didn’t come through (I’ll work on that, too). Could you mail me the code or post a test page?
@paul: What are you referring to with “update validation”?
There is a little stupid issue with the required-method: It doesn’t matter what you specify as a paremter, once its present, its always required.
@pbcomm: Yeah, gonna fix that. Thanks for reporting.
@Thijs: I had some rather complex regex included for email-validation. I had to remove it to get the plugin working in Rhino. Any help on finding a correct email-regex that works both in browsers and in Rhino is highly appreciated.
It appears your current plugin v1.1 doesn’t work with the latest jquery v1.1.4. It works great with v1.1.3.1.
@Justin: At least the latest revision works with 1.1.4. Is there a specific error?
Here with IE doens’t work with new 1.1.4 jQuery. But FF works.
Hi Jörn,
I am referring back to my post (and your reply) on 07 August at 02:08. It appears to me that there are no JS events triggered when the user uses the Browse button to select a file for a file input element. If this is true, I do not think there is a way to reliably apply a validation rule to a file input element. Does this make sense to you?
thanks,
Mike
Hi! have some problem getting validator to work on konqueror 3.5.5 (Mozilla/5.0 (compatible; Konqueror/3.5) KHTML/3.5.5 (like Gecko)).
Testsuite say:
29. validator module: hide(): container (1, 2, 3)
1. Error label not visible at start
I have problems with 1.1.4. & IE.
The “error label” doesn’t appears in combobox
This is working fine in FF2 and Safari, but I can’t get it to work in IE6 or 7 – I’ve compared mine with the demo line by line and have tried all the suggestions above, and still no luck. Can anybody figure this out?
intercession.iamdanielmarino.com/test
Thanks
Dan
Hi Jörn,
Your plugin is awesome. I have been searching though for how I can escape a value that is in there and treat it like it is null. For instance I have a text input like this:
FYI, there are some onblur/onFocus to remove/insert the “instructional value” in it as well but not shown above because I don’t think they matter to my question – if needed let me know.
In my validation, how do I treat the “instructional value” as a null so that it will still be flagged as a null. I know how to do it simply with std js just not with your plug in.
I need something kind of like this but not sure how to do it or if there is a better way (new method notEqualTo):
Thanks,
Jeremy
Hello!
I have a question: how I can replace default error messages (for example message that shows if ‘required’ validator fails)?
Hi Jörn,
I’m having a bit of a problem:
I want to attach a function for a maxValue field but I can’t get it to work. I’m wondering now if it is supported at all? (it is for the required field)
I’m trying this:
a_field: {
digits:true,
maxValue: getNP_Val,
required: true
}
…
function getNP_Val() {
return $(‘#depend_field’).val();
}
Thanks,
Mike
Hi!
I can’t get validator to work with jquery version 1.1.4…
I don’ seem to be the only one with this problem. Does anyone have any idea?
I’ve posted an example in http://69.80.208.158/demo1/validator/ with both jquery 1.1.2 (works fine) and 1.1.4.
thanks,
antonio
I have the same problem Antonio. The errormessages show up fine in Firefox, but not in IE…
hi Jerem
i have same problem with u, follow is the additional method. hope can help u.
jQuery.validator.addMethod("notEqualTo", function(value, element, param) {
return $(param).val()?(value != $(param).val()):(value != param);
}, "error");
Sure ima not the first, but when somewhere in the form exists an element with name and/or id =”cancel”,is impossible to validate it!
Hope it can be fixed.
i’m having the same jquery 1.1.4 issues as antonio and mike. i have tested against jquery 1.1.3 as well, and added opera to the mix. all appear to be working well, w/ the exception of jquery 1.1.4 + IE 7 (haven’t tested in IE 6).
for jquery 1.1.4 , the validation plugin ‘s showLabel method must be modified .
the line
label = jQuery(“”)
should be replaced with
label = jQuery(“”)
then u can see errormessages under IE again
oops , why the codes above being filtered out
replace the line in method “showLable”
label = jQuery(“<” + this.settings.errorElement + “>”)
with
label = jQuery(“<” + this.settings.errorElement + “></” + this.settings.errorElement + “>”)
note the SBC case should be replaced with DBC case by yourself.
check this out:
http://www.zeali.net/entry/534
IE7 validation issues…
Hello, I am using the latest version of jquery and your plugin. I have included the exact same files and functions listed on your sample page. And I have followed every example and suggestion I can find and yet still validating dropdown boxes is not working right in IE7. It works fine in Firefox 2. The text input box validation works fine in both browsers. The problem is not that it is not checking it, it is that It will not display my error message at all in IE7, yet FF2 shows it just fine. It does however prevent you from proceeding until you have filled in all of the required drop down inputs.
I wish I could just have all my users run FF, but that is not possible. Most run either IE6 or IE7. I have already tried multiple variations on the “ISO-8859-1″ parameters and metadata, but that doesn’t help at all. Any suggestions? Ideas? Places to look?
Thank you for an excellent script!
I am trying to use my own submitHandler which submits the form/results into a div on the same pages:
submitHandler: function send(){
var params = Form.serialize($(‘signupForm’));
new Ajax.Updater(‘signupFormdiv’, ‘help.php’, {asynchronous:true, parameters:params});
}
I have tried the following submit buttons:
and
but still the form posts to a new page instead of displaying in a div on the form page??? Any help getting the form results to post to a div on the same page using the above send() function?
Many thanks and regards
@Justin, Giuliano, oscar, Zeal: Thanks for the reports. The trouble with IE and jQuery 1.1.4 is now fixed in the latest revision and will be included in 1.2.
@Mike: Yeah, that makes sense. But at least the blur event should be triggered, shouldn’t it?
@Bacon: I don’t have access to a Konquerer testing enviroment. This may be related to the above IE issue, could you give the latest revision a try?
@Dan: The demos are still with jQuery < 1.1.4. Some change in 1.1.4 broke the error display in IE. See above for a link to the latest revison.
@Jerem: There are interesting techniques to display labels above input fields and hide them when the field gets focused. There is a good article on A List Apart about it.
@NNT: The default messages are stored in jQuery.validator.messages. Just assign something else to jQuery.validator.messages.required for a different default message for the required method.
@Mike: The maxValue method currently supports only static values, no callbacks. But the idea is interesting, I’ll take a look if I can find a nice solution for that. Until then you could just write your own validation method. The implementation for maxValue is very simple anyway.
@Antonio, Mike, Patrick, Dave: Same issue as above, solved in the latest revision. Sorry for the trouble.
@Georgi: Do you have a test page for that? I just gave it a try, and hadn’t any problems.
There is some special code to deal with submit buttons with a class “cancel”, but that shouldn’t affect normal inputs at all.
@Claude: Could you post a complete test page? The snippet you posted is not enough to find the problem.
might I suggest that on line 757 of jquery.validate.js you change it to:
: this.settings.success( label, jQuery(element) );
providing a reference to the element that succeeded validation has proven very useful to me…
Thanks, that fixed the IE problem.
@Steve: Good idea, I’ll add that.
@Patrick: Cool, thanks for reporting.
Hello,
I have problems figuring out how to set up validation on a form that gets multiple inputs generated dynamically. Is there a way to add rules not to a specific input in the form but to a jQuery selector that matches all the inputs given a pattern?
Example,
$(...).validate({
rules: {
// this selector matches multiple inputs that have ID attribute
// starting with "something", example:
$("input[@id^=something]"): {
required: true
}
}
)};
My brain is about to SIGFAULT
Thanks a lot for this great plugin.
Hi Jörn,
Right now I have a password recovery page which, when the user enters their email address, the recoverpassword.php page outputs to a div without page refresh using the following script:
function send(){
var params = Form.serialize($(‘TestForm’));
new Ajax.Updater(‘passwordformdiv’, ‘recoverpassword.php’, {asynchronous:true, parameters:params});
}
Login Details Have Been Sent…
What I would like to do is include validation into this form and when the form is submitted have the recoverpassword.php page output to the “” area using the send() function.
I have tried the following to no avail – recoverpassword.php opens in a new page instead of in the :
jQuery.noConflict(); var $j = jQuery;
$j(document).ready(function() {
$j(“#TestForm”).validationAideEnable(null, send);
});
function send(){
var params = Form.serialize($(‘TestForm’));
new Ajax.Updater(‘passwordformdiv’, ‘recoverpassword.php’, {asynchronous:true, parameters:params});
}
Basically what I’m after is to have the form validate as usual then upon clicking the Sumit button execute the send() function.
Could you provide any info as to what I’ve done wrong (I’m very new to ajax.js!)
Many thanks for your time, Claude
oops – my “form” has been stripped from the above post:
START:
form id=”TestForm”
INPUT type=”text” name=”email” size=”30″ value=”"
input type=”button” onClick=”send();” value=”Submit”
END form
@Jörn: Thank you for help!
Hi,
quite a stupid problem.
I am using the plugin to submit an easy form:
I want to bind the success validation to a function that render visible a loading bar.
So simple validation code:
$().ready(function() {
$(“#treeform”).validate();
});
Function bind to submit form:
$(document).ready(function(){
$(‘#treeform’).submit(function(){
$(‘.loading’).css({visibility:’visible’});
});
});
An idea to make the second happen only if the validation process is ok?
Thanks
Andrea
Thank you for this wonderful addition.
I would like to add validation based on ajax returned values, such as if a username is already taken or is available.
Could this be done using this plugin?
If so, any pointers?
I found a similar post above and have been able to implement this using remote:
Thank you again for your wonderful plugin!
Hi,
how may I bind a function to fire only if the validation process is succesfully.
I mean I need to fire a function only if the form fileds are validated and forms will be submitted.
Thanks for any help
Andrea
Hello,
This is excellent script, thanks.
When i open this [http://bassistance.de/jquery-plugins/jquery-plugin-validation/] page in Firefox2 latest version it displays blank, then i use Opera then only i got this page.
thanks.
@zero: You could just generate those elements with metadata, that way you don’t have to specify the rules explicitly via the rules-option. You need the metadata plugin for that to work. There are plenty examples, and the syntax is nearly plain JavaScript. Let me know if that works for you.
@Claude: It looks like you are mixing a lot of stuff, but I can’t see this validation plugin in use anywhere. Have you tried to use the jquery form plugin together with this plugin? There is a demo page that shows how you can integrate those two.
@Andrea: Just use the submitHandler-callback. That is called only when the form is valid.
@Chris: Great to hear the remote validation works for you, even without being officially released yet. I’ll try to get 1.2 out the door as soon as possible.
@palPalani: Thanks for reporting that. Unfortunately I still have no idea what the source of that ugly issue is. Its really annoying.
Hi Jorn,
I think jQuery version 1.1.4 has just broke your code in IE6. Can you help to verify this ?
@zeal: Thanks for that! Now the error labels are showing up in IE7
@Roland: Yes. This is fixed in the latest revision. Sorry for the trouble.
is there a way of throwing an error if some one leaves a drop down list on “select country”, in the code below? couldnt find this in your examples. excellent plugin btw, i use it on plenty of projects.
select country
germany
etc
@stef: Just define a required-rule for that select and set the value of “select country” to an empty string. There is a demo with selects available.
Hi Jörn!
Thanks for the great plugin!
I’m still having trouble with the error labels not appearing in IE6, even using the latest revision of the plugin.
If you could take a look, here is my code: http://paste.lymas.com.br//?q=7370
It works perfectly in FF2 (damn IE…).
Tks!
Hi,
I’ve tried to use the latest trunk version for validating a sign-up form together with jquery 1.1.4, but I cannot get ajax validations to work properly. I suspect your milk-testcase will break on jquery 1.1.4 aswell. I tried to replicate the milk test as closely as possible but it did not work with jq 1.1.4–when I switched back to 1.1.2 it did work, at least with the version of validate.js that was used with the milk demo.
What happens is that when an ajax-field is correct, validate seems to run through all fields and highlight them with error messages, when it should really just show an error for the ajax-field.
Browser is FF2.0.0.6 on os x
Any ideas on this?
I have the following code…….
$(document).ready(function(){
$("#facilityLocatorForm").validate({
errorClass: "invalid",
errorLabelContainer: $("#messageBox").addClass("errorbar"),
wrapper: "li"
});
});
Facility Locator
Zip Code:
Radius:
Search
This is just like your example only I’m trying to add a class to errorLabelContainer when some isn’t valid. What happens though is that class appears to be applied right away. Any idea why?
Jörn,
Please, forget my previous comment. That was something I was doing wrong… The plugin is working perfectly also in IE6 now.
Sorry for the inconvenience (and my poor english… I speak portuguese).
Tks!
I am new to this plugin. It looks great so far. I want to find out what is going on here because I must be missing a variable or something.
I just want to do some very simple validation, such as:
$(“#fss_form”).validate({
errorClass: “invalid”,
errorLabelContainer: $(“#jsFormValidation”),
wrapper: “div”
});
It works fine, but after I submit a form that is not valid, I get an error message, which is good. But then when I go to fill in that specific form field which was invalid, when the form becomes valid, my entire container gets set to display:none and the page appears to disappear?
Any idea what I am missing ? Thanks in advance…
@Eric: I need to run some tests with ajax validation and 1.1.4. I hope to get 1.2 out the door soon, expect it to be fixed then.
@MichaelN: Your code selects the element, adds the class, and then passes the result to the validate plugin. Thats the way jQuery works. What you want to do is add the error class to the error container when it is invalid, right? I’ll look for a solution for that.
@Matheus: No problem. I’m glad to hear it works!
@Buster Rhymes: The error container is automatically hidden when the form is valid. Moving the container out of the form (above or below it) should fix the problem.
Here is a sample function based off one I wrote in PHP for validating a US phone number. I like it better than the one from May, because it is actually validating a phone number and not just ten digits.
matches things like
1(212)-999-2345
or
212 999 2344
or
212-999-0983
but not
111-123-5434
and not
212 123 4567
Thanks Matt! I’ll add that one to additional-methods.js.
unfortunately, my method did not allow for blanks so phone would have been always required.
I would change
if (phone_number.length <= 9) {
return false;
}
to
if (phone_number.length == 0) {
return true;
}
else if (phone_number.length <= 9) {
return false;
}
and I wrote a method for a US zip code:
valid zips are either five digits or five + four digits (with optional ‘-’ or ‘ ‘ between)
jQuery.validator.addMethod("zipcode", function(zip) {
// matches US ZIP code
// allow either five digits or nine digits with an optional '-' between
zip = zip.replace(/^\s+/, "");
zip = zip.replace(/\s+$/, "");
if(zip.length == 0) {
return true;
}
if(zip.match(/^\d{5}([- ]?\d{4})?$/)) {
return true;
}
return false;
}, "Please specify a valid US ZIP code");
the question this brings up is the naming of the methods? In the US it is called a ZIP code, but the better generic term is postal code, so don’t know if you want all your functions to be US specific, but the naming of this method assures it is valid for US only.
@Matt: Thanks for those additions.
The naming isn’t an easy task. So far I used name + locale, eg. dateDE, dateITA, which isn’t perfect either, but at least its obvious.
Im trying to create a custom method that will take the value and lookup the value in a database and then confirm if the value exists or not.
Sadly i cant seem to get it to work correctly – the code is below
jQuery.validator.addMethod(“usernameCheck”, function(value, element){
$.get(‘/ajax/usernames.php’, {q: value}, function(data){
if(data == “true”){
return false;
}
return true;
});
}, “This username has already been registered”);
( http://pastebin.ubuntu-uk.org/398 – for better highlighting )
It just return the custom error msg each time
That is exactly what I want to do Jorn. Second question though.
One of the examples I looked at had a div that contains and ol. When an item is invalid the div goes from hidden to displayed and an error is inserted into an li element. When the item is no longer invalid the li is removed but he div is still displayed. Is there a way to make the div go back to hidden as well? (This is from the errorcontainer-demo.html example) Thanks.
@Phunky: The latest revision provides a remote-method – that should do exactly what you need. Usage is very simple, just specify a rule like this:
The value is sent as a parameter “value” and the method expects are boolean return value, eg. true, false, 1 or 0. There is also an example.
@MichaelN: I’ll look into that as well. The error container options definitely need more work to get them into a useful state. Your feedback is highly welcome!
@Jorn: Thank you, that is great it works a treat now
@Jorn: Thanks so far I love this library.
Upgraded to jQuery 1.2, now error messages don’t display in IE6/7. FF, as usual, is just fine. Form elements still change classes (red outline) with no problem, but the actual message that gets appended to a new label after the element does not show.
Here is my code:
jQuery().ready(function() {
jQuery(“#Fundraising”).validate({ submitHandler: sendMyForm });
Nothing spectacular.
Anyone else seeing this?
Hi, I am usig your plugin but I have one question, I make a json with the same characteristics of the validator map, but when i assign to form validate it seems to don’t do anything…..is something like this:
jsonValidate = “//…string json build…//”;
$(“#myform”).validate(eval(‘(‘+jsonValidate+’)')).form();
alert(jsonValidate) [type string (previous eval)] => result:
{
“errorElement”: “div”,
“errorClass”: “field-error”,
“rules”: {
“add_manual_name[1]“: {“required”:”true”},
“add_manual_email[1]“: {“required”:”true”}
},
“messages”: {
“add_manual_name[1]“: {“required”: “put name”},
“add_manual_email[1]“: {“required”: “put email”}
}
}
i need some help please!!!
@ Jörn:
Have you considered coding to allow the new div to be a floating pop-up off the submit button?
I ask, because that’s exactly what I’m attempting to do – I’m hitting a few roadblocks, bu tI know it’s the limitations of my knowledge, not the plugin. If I can’t figure it out soon, I’ll post my code and see if you can see something I can’t.
Hello again. I am running into an issue where I cannot validate the inputs in a row that was cloned (using jQuery) from a hidden row. I have three inputs: length, width, and height. On the same form at the same time the validation for drop downs and text inputs work just fine. The just don’t work in the text inputs created with the clone tool. I have to do this so that I may add as many items as the user wants to the screen at any moment before the form is sent to the processing script.
I have tried it in IE and Firefox and it simply doesn’t work. I am using the attribute class=”{required:true}”. Any suggestions or is this something the validator cannot do right now?
Here is the javascript function that creates the new input fields:
blank = $(‘tr.hiddenpallet’);
newitem = blank.clone().insertBefore(blank).removeClass(‘hiddenpallet’);
This is wrapped in a ready function. I have tried the class with and without the first class name (ex. class=”len {required:true}” and class=”{required:true}”).
The curly braces surrounding the required:true seem to work the best for my site and they have worked on everything up until now.
Thanks,
Patrick
Hi Jörn,
Thanks for the great plugin.
I have bumped into an issue I hope you could help with.
I’m trying to use validation and blockUI at the same time on a form – actually I’m using lot’s of plugins on the form (jquery.form.js for ajax, jquery.maskedinput.js, and jquery.blockui.js).
I could get them work together except that blockui fires even if the form is invalid. What happens is that by submitting a form with blank required fields, the error message is displayed beside the invalid input, but the blockui is fired and freezes the page.
I think before firing blockui I should check if the form is valid. Currently I have put the blockui trigger inside the pre-submit callback of jquery.form.js which handles the ajax submission.
Is there a method to check if the form is valid so that I use it like this?
if (formvalid) {
…
$.blockUI();
return true;
} else {
return false;
}
One more thing – I need to retrieve json from the server in response to my ajax call and it is very easy to do that with jquery.form.js; so I cannot leave that and use ajaxSubmit as is in one of your examples. (actually, ajaxSubmit might be as powerful as form.js, but I have very limited experience in js and have to resort to modifying examples and code samples).
Many thanks,
Majid
Hmm. I’m glad you’re not using that validator on your comments, because it doesn’t like my email address.
“+” is a legal character in email addresses (really, it’s amazing how little isn’t a legal character…)
Is there any reason why the remote method triggers all error messages to display when you have corrected it’s error?
Try your demo page – Type Peter, then removed the “r” all the error messages will display for the other items.
Did jQuery 1.2 just broke your code ?
The onKeyUp validation is not working. Meaning that when it first validate, there will be error messages prompting beside the form element. When the user try to correct the data, the error message doesn’t remove by itself where your demo actually removes those messages(meaning revalidate the data again). I am testing on jQuery 1.2, please verify on whether your plugin supports jQuery 1.2 or not.
Thanks a lot.
The error messages ain’t appear in IE6 as well.
Hello, first … thanks for this great plugin, it’s a savior for my project.
At first, I thought it was working perfectly, but I noticed if I submit the form and the form has no errors, it works as I would expect. But if I submit the form and have an error, after i fix the error and click submit again … it submits the form twice.
It seems to queue up the submissions … if I click submit and have to fix errors 2 times, on the 3rd click of submit it posts the form 3 times.
I ‘m using the Form plugin.
The form is loaded dynamically into the page via load(). I might not be understanding ‘binding’ or something … I don’t know.
Here is the code I use to trigger the form that’s dynamically loaded in.
if ($(event.target).is(‘.buttonName’)) {
var form12 = {
target: ‘.myDiv’,
url: ‘form-processor.php’,
type: ‘post’
};
$(“#myForm12″).validate({
submitHandler: function(form)
{
$(“#myForm12″).ajaxForm(form12);
}
});
}
oops … my code was incorrect, it’s
$(”#myForm12″).ajaxSubmit(form12);
not
$(”#myForm12″).ajaxForm(form12);
(form does work … but i need to click the submit button twice to get it to fire)
@Nick: Please give the this demo for an example of adding inputs to a form.
@Majid: Please try to put blockUI and ajaxSubmit into the submitHandler-callback of the validation plugin. That way its only called when the form is valid.
@Karan: I’ll readd that. I had a much more complex regex before, but that caused a few problems in Rhino. Just adding the + should be enough.
@Punky: Thanks for reporting that bug. Hadn’t noticed it until now.
@Roland: The latest revision is compatible with jQuery 1.2, I just haven’t got around to make a new release.
Thanks for reporting anyway. I’ll look into the onkeyup issue, that is definitely broken.
@Greg: Try to call ajaxSubmit inside the validation submitHandler.
Both ajaxForm and validate register a submit handler, you have to avoid using both.
See this example.
Jörn,
i’ll check that out. but i’m just calling …
$(”#myForm12″).ajaxSubmit(form12);
i’m **not** calling both ajaxSubmit and ajaxForm at the same time.
so the complete code looks like …
if ($(event.target).is(’.buttonName’)) {
var form12 = {
target: ‘.myDiv’,
url: ‘form-processor.php’,
type: ‘post’
};
$(”#myForm12″).validate({
submitHandler: function(form)
{
$(”#myForm12″).ajaxSubmit(form12);
}
});
}
I think it has something to do with the fact that i’m using load() to add the form the DOM.
Here’s the complete code … and thanks for your bassistance!
$(document).ready(function() {
$(‘body’).click(function(event) {
// #1 – load up the form. code to bring the form into the DOM
if ($(event.target).is(‘.partInfo’)) {
$(“#formContainer”).load(“form.php”);
}
// code to submit the form
if ($(event.target).is(‘.sendCoMailButton’)) { // my form button
var sendCoMail = {
target: ‘.result’,
url: ‘include/tab-message-sent.php’,
type: ‘post’
};
$(“#sendCoMailForm”).validate({
submitHandler: function(form)
{
$(form).ajaxSubmit(sendCoMail);
}
});
}
});
});
Jorn,
May I know when is your new release going to be ? Thanks .
Solution! Amen … I’ll be honest, I guess I still don’t fully understand how to bind, how to see if it’s bound or how to release it.
But here’s what made it work …
$(“#sendCoMailForm”).validate({
submitHandler: function(form) {
$(‘#sendCoMailForm’).unbind(‘submit’).find(‘:submit,input:image’).unbind(‘click’); //this is the magic fix, unbinding it.
$(form).ajaxSubmit(sendCoMail);
} });
Hi Jorn,
I am preparing a ColdFusion Custom Tag for easily using your plugin in CF markup.
I have a problem with IE and Opera.
Note: I am using validate.pack version 1.1, metadata.js and jquery 1.2
IE7:
MyCode is:
$(document).ready(function(){
$(“.cfjq_form1″).validate()
});
This code is working with JQ 1.1.4 but now simply block the submission but do not display the errors.
I obtain the same problem trying to place the errors in a separate box like this:
$(document).ready(function(){
$(“.cfjq_form2″).validate({
errorContainer: $(“.messageBox2″),
errorLabelContainer: $(“.messageBox2 ul”),
wrapper: “li”,
});
});
Opera works fine in the first example but fails in the second.
Firefox and Safari are working 100% fine.
Have uploaded a live example here:
http://www.andreacfm.com/examples/cfJq_forms/
Are these known issues??
Any suggestion?
Thanks
Andrea
Jorn,
Can you give me some guidance on how to fix that in IE so that I can temporarily use your plugin to be compatible with jQuery 1.2 ? The onkeyup and onblur is not as urgent. I tried to debug on why the error message not showing up in IE6, but no luck. Can you just send me the portion that fix this part ? Probably you can email me that portion of code with some instructions ? It’s quite urgent for me to fix that bug in IE6. Just send it to the email address that I’ve entered. Really appreciate it if you can help.
Many thanks.
Hi Jörn,
I continue to find your plugin to be a great time saver. I am using the errorContainer option to display a div on the form at validation indicating there are errors. However, when all of the validated elements should be passing their rules, the errorContainer is still visible. I would expect that it would hide. If I then click the submit button, it does hide. I wish to have it hide immediately after all rules pass without needing to click the submit button first. I prefer not to employ keyup or blur events in the form. Is there a way to accomplish this? Is their a validator method I must manually call to force it to hide?
Thanks for your time,
Mike
@Greg: If you have further problems, please post a test page. That’d make it a hell of a lot easier to see the actual problem.
@Roland: You need to replace the code that creates the error label. There is something like “<” + settings.errorElement + “>”. Just add a slash in front of the >, that should fix it.
@Andrea: Yes, that is a known issue. jQuery 1.1.4 changed a small bit that made code like this fail: $(“<label>”). You can get the latest revision from SVN where that issue is fixed.
@Mike: You’d have to overwrite the prepareElement method. Give this a try:
See the Proxy Pattern explanation in the jQuery wiki.
Hello again. I am running into an issue where I cannot validate the inputs in a row that was cloned (using jQuery) from a hidden row. I have three inputs: length, width, and height. On the same form at the same time the validation for drop downs and text inputs work just fine. The just don’t work in the text inputs created with the clone tool. I have to do this so that I may add as many items as the user wants to the screen at any moment before the form is sent to the processing script.
I have tried it in IE and Firefox and it simply doesn’t work. I am using the attribute class=”{required:true}”. Any suggestions or is this something the validator cannot do right now?
Here is the javascript function that creates the new input fields:
blank = $(’tr.hiddenpallet’);
newitem = blank.clone().insertBefore(blank).removeClass(’hiddenpallet’);
This is wrapped in a ready function. I have tried the class with and without the first class name (ex. class=”len {required:true}” and class=”{required:true}”).
The curly braces surrounding the required:true seem to work the best for my site and they have worked on everything up until now.
Thanks,
Patrick
Hi! Am finding this plugin VERY useful! BUT … I don’t understand how to use the addMethod() – even the ones in additional-methods.js. This is how I am trying to do it …
$(“#testForm”).validate({
rules: {
name: {
lettersonly: true,
required: true,
minLength: 10,
maxLength: 30,
},
is this a correct way to implement it? (using lettersonly:true inside a rule) ?
I’ve been using the validation plugin to check all data in a form is all right. It works perfectly in Firefox and Opera, but IE (6) is making me go crazy.
In this browser, error messages don’t appear, although the form can not be submitted.
Here comes my HTML code:
Empresa
CIF
Nombre *
Apellidos *
Direccion *
Poblacion *
Provincia *
Álava
Codigo Postal *
Telefono contacto *
Movil
Email *
DNI *
Fecha de Nacimiento (dd/mm(aaa) *
Cuenta bancaria *
And here comes my JS:
$().ready(function() {
// validar el formulario de añadir cliente
$(“#cliente”).validate({
rules: {
cif: {
minLength: 9,
maxLength: 9
},
nombre: “required”,
apellidos: “required”,
direccion: “required”,
poblacion: “required”,
provincia: “required”,
cp: {
required: true,
digits: true
},
telf_contacto: {
required: true,
minLength: 9,
maxLength: 9,
digits: true
},
movil: {
minLength: 9,
maxLength: 9,
digits: true
},
email: {
required: true,
email: true
},
dni: {
required: true,
minLength: 9,
maxLength: 9
},
fecha_nacimiento: {
required: true,
date: true
},
cuenta: “required”
},
messages: {
cif: {
minLength: “El CIF debe tener una longitud de 9 dígitos”,
maxLength: “El CIF debe tener una longitud de 9 dígitos”
},
nombre: “Introduzca el nombre del cliente”,
apellidos: “Introduzca los apellidos del cliente”,
direccion: “Introduzca la dirección del cliente”,
poblacion: “Introduzca la población”,
provincia: “Introduzca la província”,
cp: {
required: “Introduzca el código postal”,
digits: “El código postal solo debe contener números”
},
telf_contacto: {
required: “Introduzca el teléfono del cliente”,
minLength: “La longitud del teléfono debe ser de 9 dígitos”,
maxLength: “La longitud del teléfono debe ser de 9 dígitos”,
digits: “EL teléfono solo debe contener números”
},
movil: {
minLength: “La longitud del número de móvil debe ser de 9 dígitos”,
maxLength: “La longitud del número de móvil debe ser de 9 dígitos”,
digits: “El número de movil debe contener solo números”
},
email: {
required: “Introduzca la dirección de correo electrónico del cliente”,
email: “Introduzca una dirección de correo electrónico válida”
},
dni: {
required: “Introduzca el DNI del cliente”,
minLength: “La longitud del DNI debe ser de 9 dígitos (formato 12345678a)”,
maxLength: “La longitud del DNI debe ser de 9 dígitos (formato 12345678a)”
},
fecha_nacimiento: {
required: “Introduzca la fecha de nacimiento del cliente”,
date: “Introduzca una fecha correcta”
},
cuenta: “Introduzca la cuenta bancaria del cliente”
}
});
});
The CSS relative to the errors is something like this:
#cliente label.error {
margin-left:400px;
width:auto;
display:inline;
}
In the HTML are also correctly included jquery-1.1.4.js, jquery.form.js, validate.js and jquery.metadata.js.
I cannot show how it seems since it is in a private application under user/password.
Does any body help me to see the light?
Thank you very much folks!
@Patrick: You need to refresh the validator each time you update the form that way. See the Dynamic inputs demo.
@Flemming: That looks good. But it works only if you added a method with the name “lettersonly”, and that is what addMethod is for.
@Guillem: That is an issue that crept in from 1.1.4 and is fixed in the latest revision of the plugin, but isn’t in an official release yet.
Jorn,
First off — thanks for this very useful module!
Now, I think that you may have a slight bug on the first demo page http://jquery.bassistance.de/validate/demo-test/index.html To reproduce this bug, first uncomment code block below line 79, for showing/hideing the last field of the second (green) table. In FF it works as expected. In IE it just changes the DOM, but it doesn’t refresh the last field of the form, until you click away from the checkbox control. I suspect that the problem may lie in the way .change handler for checkboxes (and radio buttons!) works in IE, because if you change the show/hide action to happen on .click, everything works as expected in both browsers.
Hi Jorn,
I’ve been using validator.refresh() everytime when I have a dynamic record being created. But when a page contains records of more than 100, your validator seems to hang in many of the browsers. Is there any other way of refreshing only the created form element to the validator instead of the entire validator ?
Your feedback is very much appreciated.
I think the resetForm() is not working with jQuery 1.2.*
I was doing everything properly so I just updated to the very latest (unofficial release) and my addMethod is working now!
However, I just checked my form in IE6 and IE7 and it skips validation and gives me the following Error: Expected identifier, string or number (on line 59 apparently) – here’s a link if you wouldn’t mind taking a look: http://indstrengthdev.com/clientFiles/bayAgent/validation/testForm2.php
So, Jörn, where can I find the latest and unofficial version of the plugin? I just downloaded the one is here…:S
I also changed the jQuery version for the latest one released, I guess it’s the 1.2.1.
It’s still not working under IE (neither 6 nor 7)
What else can I do?
Thank you very much
@sloba: Thanks, fixed that!
@Roland: That is an interesting point, I haven’t considered that. I’ll try something that allows you to pass in the elements to refresh as an argument to the refresh method.
If you want to give it a try for yourself: Search for “refresh:”. Add an argument to the function. Add a check for the argument, and use that instead of the “big” selector in front of the filter-call. Let me know if you have any success, otherwise you’ll have to wait for my results.
Thanks for the hint about resetForm, I’ll give that also a try.
@Flemming: You have an illegal trailing comma in your code, in lines 59 , 73 and 85. Its easy to spot them using the Firefox extensions Firebug and Web Developer Toolbar. You need to enable strict warnings via the Dev Toolbar to see them on Firebugs console.
@Guillem: Try this.
@Roland: I’ve commited an improved refresh method. Please give a try. The related demo is also updated.
I’m really disappointed. Error messages don’t appear in ie6/ie7 with jquery>=1.1.4 With jquery 1.1.3 work fine.
Hey, Zukimo
Please refer to this post comments on “17. September 2007 |15:56″. Jorn actually teaches us how to fix that bug temporarily if you need this to be fixed urgently. Remember to get the un-packed version to modify. Hope this helps.
Cheers !
@Zukimo: That is also fixed in the latest revision.
I love the plugin and have used it on simple ul/li forms. However, I am trying to implement it in a table format (tr/td) where the field labels are only displayed in the initial TH and thus will not be displayed with each field. Ex:
First Name | Last Name | UID
George | Johnson | johnsong
David | David | anastasiud
Bob | Smith | smithb
I would implement row level validation, such as if first_name or last_name were entered on that row, then UID would be required. The field names on that row would be unique, such as first_name_15, last_name_15, uid_15, if 15 was the id of the record I was showing. Can someone please (PLEASE) help me out with an example that would do this? I would really appreciate it!
Thanks,
David
thx for the great plugin!
But the used cmxforms.js doesn’t work with jquery 1.2.1.
Any ideas?
Thanks
Klaus
Hi Jorn,
Can you help me to pack your validate.js ? I want it to shrink the size. I tried, but it was complaining the content doesn’t pass the ISO standard. That doesn’t allow me to compress using packer. I was suspecting that the charset that you use for Denmark date. As well as url method as follows :-
url: function(value, element) {
return this.optional(element) || /^(https?|ftp):\/\/[A-Z0-9](\.?[A-Z0-9ÄÜÖ][A-Z0-9_\-ÄÜÖ]*)*(\/([A-Z0-9ÄÜÖ][A-Z0-9_\-\.ÄÜÖ]*)?)*(\?([A-Z0-9ÄÜÖ][A-Z0-9_\-\.%\+=&ÄÜÖ]*)?)?$/i.test(value);
}
Btw, the partial validation is working now! as well as the onkeyup and onblur validation. Thank you so much. I am using jQuery 1.2, btw
Hi Jorn,
Can your validation onkeyup and onblur validation be turned on and off ?
@David: You can specify the dependency between fields using the required-method. Something like this:
required: function() { return $(“[@name=first_name_15]“).is(“:filled”) && $(“[@name=last_name_15]“).is(“:filled”) }
In that case it may be better to implement a custom method that searches for the fields in the DOM and checks their values:
@Klaus: Thanks for the report, I’ll check that.
@Roland: Could you give the latest revision a try? I just fixed a missing semicolon and also commited update packed and minified versions.
Great to hear both partial validation and the onkeyup/blur stuff is working, mostly. To disable them specify onkeyup: false and onblur: false via plugin options.
Unfortunately I do not always know the position of the fields I am interacting with, as the table is dinamically generated and depends on user “view” (fields the users want to actually see and edit). Thus, there may or may not be other fields in beween first_name and last_name. Thus, I can’t use prev(). I am more interested in your required function above. Can that be abstracted to something like:
required: function(rowId) { return $(”[@name=first_name_" + rowId + "]”).is(”:filled”) && $(”[@name=last_name_" + rowId + "]”).is(”:filled”) }
?
Also, I was really hoping to pass these validation rules in the class, and the actual custom validation rules (if any), would be included as a js include. I am pretty new to JQuery as well and could still use some help with this.
I’ll play around with it as well. However, I tried just a simple require on a single field (not related to other fields) in a table and have not been able to get it to work. Could you by any chance send me a full example, maybe in email? Thanks a lot for your help!
I ran into difficulty using Validate with the latest release of JQuery 1.2.1. I’m looking into opening a bug in Trac for JQuery – on IE6 I can’t seem to dynamically create elements if I don’t close the tag: ie jQuery(“”) doesn’t work in IE6 (failing silently) but jQuery(“”) suceeds… (Both versions work in FF2)
This of course breaks the showLabel method in your Validate plugin… I don’t know if this is a bug in jQuery or if it will just be documented, but I wonder if you want to adjust Validate in the meantime…
Hi Jorn,
Thank you so much. I would like ask, what is the difference in between a full version and a minified version.
A follow up to my last post – see http://dev.jquery.com/ticket/1730 – I’ve found the problem and supplied a patch…
Hi Jorn –
I’m back.. and this time I don’t think I’ll be able to talk myself out of my own issues
I have built a very robust page using both your Accordion and Validation plugins, on my first attempt at using jQuery for a client site.
http://comparemyagent.com/forms/fa_sell.cfm
First of all, thank you for 2 great plugins…do you have a wishlist somewhere?
I’d like to give you at least a little something for your troubles.
Secondly – while things are mostly working, I still need some help, for which I am willing to pay you, or another user, to get some small things sorted out.
The problem is, I am supposed to have this done tomorrow and then make another 6 forms with similar functions for this site!
Here are a few more things I need to add to the base functionality:
1) Now that everything is working as it should for a single form, I need to break this into two ‘validation groups’ somehow. Perhaps an ID on each fieldset?
The idea is to have each of the next or submit buttons validate the fields in its panel. For example, at the bottom of the first panel is a button for ‘next’… if no errors, it should go to Panel 2 as it does now … but if there is an error, it should not go to next but should show the red error messages for the fields in the first panel. Once validation errors are fixed, that same button should allow going to the next panel.
2) I’d like a js alert box to be shown at the same time the validation is run, saying “Please correct the information as shown in red”, so the user sees very clearly why the next or submit button did not work. Then they can close the alert popup, fix the errors, and move forward.
Here are the errors I am struggling with, by browser:
// in IE 6
- once ‘submit’ is clicked, and validation shows, you cannot go back to the first panel
- validation response seems slow
- clicking submit a second time allows the form to be submitted, even if no validation errors are fixed
- my buttons have css to indent the text off of the page, showing only the background image – but for some reason they have an underscore or a dash (like a linked blank space?) … I have styled it to be white but it is still visible, need this to go away.
// in IE 7
- validation messages are in a tag, yet they are triggering the border from my css style for a ‘fieldset’. You will see a green border under most of the error messages (but not all of them)
This is very strange.
- same problem with not being able to go back after submitting / validating as IE6
- same underscore character in my buttons as in IE6
- same problem with being able to submit if submit is clicked twice as IE6
// in FireFox
- the accordion panel height seems to vary. Sometimes, on load, the bottom buttons are not visible, other times just fine.
What do I need to fix or change in my markup or css to make this work correctly? I have tried a number of things and can’t get it right.
// Safari
I do not have a mac. but I am being told that the page simply falls apart, no form visible on second panel, etc… any ideas?
As stated I am VERY WILLING TO PAY for someone’s time who can fix these things.
Anybody able, I’d be greatly appreciative… been on this for a long time now and I *must* get it all working, (and quickly, or I am in trouble) !
I am sure most of the trouble is of my own doing, but I am at the point where I can’t go any further without some help.
Thanks in advance… I’ll be checking back here regularly, and eagerly, throughout the day tomorrow.
Hi Jörn,
I cannot get onkeyup to work. I have the latest version of jQuery and your latest version of jQuery.validate from last night. Onblur and onsubmit both work fine, and both can be disabled. But onkeyup seems broken, in that no validation happens as I type in the form.
I have been away from our validation implementation for a few weeks, so I didn’t notice this before.
anyone can tell me what is the validation function for
domain name or ip address
Sorry Jörn — my mistake. Onkeyup works fine! Turns out I had forgotton all about our previous discussion concerning immediate validation. You mentioned implementing an option to switch on immediate onkeyup validation, which would default to being off. Has that been implemented?
Jorn,
I too have an interface where immediate blur validation is preferred. I have tried hacking the “require” function switch case without success. Do you have any recommendations for hacking this on my own?
Much Thanks,
Chris
I was able to get the table row validation to work. See example at http://www.rfcmultimedia.com/table.html
However, still having trouble with error placement. I need the error to be displayed underneath the input field, not to the right as it does now. It should also wrap around if the text is longer than the width of the input field. I am ok with adding another element inside the table cell ahead of time but the should not be there initially. It should only be added when an error is displayed and removed when the error is taken away.
I like having the text in the same cell as the input box because there will be a lot of cells and I want to make sure the user knows which cell has the problem. In the current example, however, the text in the input box changes styles as well. I’d rather only the error message have the custom text style (red, italics), and the input box have a dotted red line, but the text in the input box should remain unchanged.
Any help from anyone will be greatly appreciated. Thanks!
Hi Jörn,
I noticed a problem in Internet Explorer 7 when the Google Toolbar is installed. If you have the AutoFill feature enabled, it can conflict with error messages.
For example on your Tests and Examples page, with the AutoFill feature enabled to enter a name and e-mail address, the first two fields on the page are displayed in yellow to let you know you can use AutoFill.
If you leave them blank and click submit, the text that should be an error message reads: “Your Google Toolbar can fill this in for you. Select AutoFill”
I’m using the validate plug-in on a page with a custom errorPlacement handler and the only error message I get provided is the Google Toolbar message.
Any ideas? Thanks again.
Follow up to my previous post, it looks like Google Toolbar is modifying the element title in IE 7 but not Firefox. So the formatAndAdd function takes the Google Toolbar text instead of the validation error message.
Hi Jorn,
I have one big question for you. During the document ready you basically initialize the validator as
var myValidator = $(“#form”).validate();
…and at later stage, will be using this variable to validate again using
myValidator.form();
Can I avoid from calling $(“#form”).validate(); during the page load but register the form elements at the later stage by on-demand scenario. Meaning that, when user click “add” or “edit”, then only register those form elements to the validator for validation at later stage during form submission ? Instead of validating all of the field which might not be “dirty”ed by the user. Is this possible ?
If this can be done, it will definitely making the performance to be boosted. Please advise, thanks.
update: I think I found another IE bug… weirdest thing… I have my form in an accordion panel as you have seen, made of LI for each panel. And then, I have a group of form fields in a fieldset, all inside the LI. Not the smoothest markup perhaps, but it is working just fine.
Anyway, when using any inline element as the error element (label or span) and *when font-style:italic is applied via css for the error class*, IE7 puts the same top border style on each error label as is on my fieldsets. Totally whacked. To explain – I have a green border on the fieldset. When hitting submit in IE7, each of the labels appears to the right of the error field as it should, but with a green top border all the way across the page, with a gap where the ‘legend’ appeared in the true top fieldset border.
I was so stumped on this, I narrowed it down by gradually removing css styles – setting border-top:none on my fieldset kept the border from appearing on the labels, so this is how I knew what was getting mirrored. And then I narrowed it down to the italic font style. What the…??? I know… but its true. Taking italics off of the text style for the error labels made it so it didnt happen any longer.
(note – I have a top dotted border on my error label styles now as per client request.. this is not the same – the problem border was all the way across the page, right through whatever field happened to be there, obviously a display error … and very very strange! and more proof to me that IE7 is just a bucket full of problems)
nothing for you to do about this, just a really strange phenomenon I managed to uncover (i think I am a browser bug magnet!)
Update on long error post above (thanks for your patience the last few days with all my insanity!)
I have managed to solve everything except
a) In IE 6 and 7, clicking submit button one time shows errors. clicking it a second time allows the form to be submitted with no errors being fixed. is this a bug?
b) still need to sort out the correct code, if possible, for validating part of the form when a button element is clicked, and interacting with accordion so that on click, validation is run – if valid, next panel is shown, if not, showing errors and keeping accordion from advancing.
Is this possible?
that’s it… everything else I was whining about seems a-ok at this point.
Wanted to drop by and give thanks for your awesome jQuery plugin Jorn.
I also wanted to throw in a little note: the plugin wasn’t working for me with IE6 and IE7 – took me four hours to figure it out but the problem was not the plugin; it was in my ‘addevent.validate.js’ file (which I added rules to). I had a ‘comma’ trailing the last rule in the file and was tripping up both IE’s. Fix is obviously to remove it because no other rules are following it!
Hope that helps any noobs (like me).
Hi,
I am using this plugin along with jquery form plugin. I am using the error container, but i don’t want it to validate the form on any event other than submit.
I have tried putting in event: “submit” and onsubmit: true – but nothing seems to work? It still validates when i loose focus to a textfield?
Any help appreciated, below is the code. Ta.
–
var container = $(‘div.msgError’);
var v = jQuery(“#”+formId).validate({
onsubmit: true,
event: “submit”,
errorContainer: container,
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
success: function(result) {
if(result.status)
{
v.showErrors(result.data);
v.focusInvalid();
}
else
{
$(‘#ajax_response’).html(result);
$(‘#ajax_response’).show();
}
}
});
}
});
–
I got error with jQuery 1.2.1:
Error: jQuery(element).data is not a function
Source:http://localhost:4321/content/js/plugin/jquery.validate.js
Line:895
This occurs in both FireFox 2.0 and IE 6.0.
The markup:
Your Email
You may get replied through this email address.
Title
Subject of your message.
Message
Words you’d like to say.
The script:
$(document).ready(function() {
$(‘#email’).focus();
$(‘#contactForm’).validate();
});
@David: Yes, you can abstract that as a factory method, and call it like this:
required: createRequiredFor(rowId)
createRequiredFor must then be a function that returns a function:
function createRequiredFor(rowId) {
return function() {
$(”[@name=first_name_” + rowId + “]”).is(”:filled”) && $(”[@name=last_name_” + rowId + “]”).is(”:filled”)
}
}
See the Dynamic Totals demo for reference to validation with table layouts. Though currently that demo is still a bit buggy.
The issues you describe with error classes should be solvable by tuning your stylesheets. The rest just needs a good errorPlacement implementation. I’d need to see a test page to provide more concrete help for that.
@metapundit: Thanks for the report. The issue is fixed in the latest revision.
@Roland: The minified version removes all comments and whitespace.
@Ermath: Nope, the immediate option isn’t there yet, but will be included in 1.2.
@raghav: You could start with the url-method for domains, though there isn’t any for IPs yet. But finding a regex for IPs should be easy, with that you just need to copy on the of the existing methods and replace the regex.
@Jose: You can avoid that issue by providing an error message for that field that has a higher priority then the title attribute. The plugin checks custom messages, specified via the messages-option, first, then the title, then default messages.
I don’t want to completely remove the title-support, but I also don’t see any other solution. Ideas?
@Roland: The latest revision allows you to pass elements to the refresh-method, and only refresh those. Thats great for adding new elements, though it doesn’t avoid validating all elements.
@ben: You need to specify onkeyup:false, onblur:false and onclick:false to disable any validation other then submit.
@deerchao: Looks like you haven’t included the metadata plugin. See the dependencies section on this page for details.
Thanks for all your help so far. Please see my test implementation at:
http://www.rfcmultimedia.com/table.html
I still need help with the error placement. I’ve been playing with CSS but no luck. I need the error to be displayed underneath the input field, not to the right as it does now. It should also wrap around if the text is longer than the width of the input field. I am ok with adding another element inside the table cell ahead of time but the should not be there initially. It should only be added when an error is displayed and removed when the error is taken away.
I like having the text in the same cell as the input box because there will be a lot of cells and I want to make sure the user knows which cell has the problem. In the current example, however, the text in the input box changes styles as well. I’d rather only the error message have the custom text style (red, italics), and the input box have a dotted red line, but the text in the input box should remain unchanged.
Hi Jorn,
Thanks for your reply. But my question was how can I NOT to validate ALL of them. I just want to validate a portion of it. I believe when the page load, you have already register those form elements that exists in the form, am I not right ? So when click submit, you will basically validate the ENTIRE form. I would rather validate only those which are “dirty” (entered by user, or edited by user – on demand basis) to be validated. Is that possible ?
If yes, how should I initialize the validator ? Currently how you initialize is by using var myValidator = $(”#form”).validate();
Please advise
Yes, I know that you can add the new form elements by calling refresh(partial); But before that, how should I initialize the validator ?
p/s : sorry for those capitalize word, I just want to emphasize my “problem” to you :p
Hello everyone,
It doesn’t seem possible to display an error message under a select tag.
e.g. a list where user can choose his religion, the first item is “Select” because I want to be sure he selects an item :
[...]
religion: {
required: function() {
return $(“#religion”).val() == ‘Select’;
}
},
[...]
religion: {
required: “religion required.”
},
[...]
Religion (visible)
Select
Christianity
Orthodoxy
Muslim
Buddhism
Judaism
Atheism
[...]
I can see by displaying an alert that it enters the required custom function, but no error message is displayed.
Thank you for any kind help !!
Hi and thanks for the terrific script! I’ve tried quite a few out over the past week and yours is the only one that gets me really really close to what I need to have happen with my form.
I have posted a working version of one of your demo scripts here (http://issuelab.newmediastage.org/system/application/scripts/js/jquery/demo-test/ajaxSubmit-intergration-demo.html) . All I’ve done is add a comment textarea that uses tinyMCE. (By the way, your script is the only one that even let’s me see the wysiwyg buttons on the textarea – thank you!) I’m running into what I’m learning is a very common problem — you have to click submit twice to get any validation info on the comment field. I understand this is because tinyMCE tucks textarea input into a hidden field until it needs to do something with it. And that the validation script doesn’t know it’s there until it’s been moved into view, so to speak – that’s what happens on the first click. The second click actually triggers the validating.
The fix that I keep seeing all over the web is to add tinyMCE:triggerSave(); somewhere — but where? I did se your posts at http://groups.google.com/group/jquery-en/browse_frm/thread/f649148d8ff5511a pertaining to this issue, but I haven’t been able to find the actual fix for tinyMCE implmentations.
I am really new to all things asynchronous JS. Not new to tinyMCE or PHP though. I appreciate any pointers, clues, hints, script rewrites!
Thanks!
Hi Jörn,
Thanks for the reply. I know for custom validation rules, the correct message is used, but for the standard rules, such as “required”, the element.title is checked before the validator messages. Maybe, the element.title should be checked last, before the “no message” warning?
From the formatAndAdd function:
var message =
this.message(element.name, rule.method)
|| element.title
|| jQuery.validator.messages[rule.method]
|| “Warning: No message defined for ” + element.name + ““;
Hi Jörn.
i have found a serius flaw in your validator.
I see that in you use Jquery 1.1.2 in http://jquery.bassistance.de/validate/demo-test/
But if you use the latest JQuery (1.2.1), Internet Explorer will not show the error labels.
I guess i have to use JQuery 1.1.2 until you know what the problem is.
I found a fix for IE not showing the error labels with jQuery 1.2
on line 739 change,
label = jQuery(“<” + this.settings.errorElement + “>”)
to:
label = jQuery(“<” + this.settings.errorElement + “/>”)
The ending slash allows it to parse the element correctly. Not sure why it’s needed, but it is.
If the commenting system screws up on that code change, just add a / to the end of the generated HTML element on line 739.
Hi,
using regulary validation plugin.
My problem is allow a field to contain only 8 carachter (only letters
or numbers) but no white space.
I am really bad with regex.
Any Help??
Thanks
Andrea
Thanks Jorn, works great.
Hi Jörn,
cool script, thanks. There is just one thing with the blur event I don’t
get. I checked out the demo http://jquery.bassistance.de/validate/demo-test/custom-methods-demo.html
but didn’t see, how to implement you code snippet from above.
Where do I have to put it that the error messages appear also on
an blur event?
Thanks indeed
Florian
Ok, forget it. I got it now.
I used another validation script before. There the blur validation was
working in a different way. When you clicked into a required input field,
entered something wrong or nothing and left it, the onblur event was firing an error message at once.
Hi Jorn,
your plug-in is really great ! I’ve just a question:
is it possible to concatenate more than one check for a property ?
An example:
required: “#multiuser:unchecked” AND “#otherfield:filled”
If yes, is it possible to use the AND and the OR logic both ?
Thanks
Great plugin! The only question I have is, I don’t understand how to submit the form after it’s been validated. My php code is on the same page as my form. I see where to edit the submit handler and change it from alert to whatever but, I don’t understand what to change it to.
Are there any known issues using the validation plugin with IE? I’m getting an error “Object doesn’t support this property or method”. that happens just when loading the form.validate() function.
@Matthew: Could you post a test page for that?
@tinawina: I’m planning to add a beforeValidation callback that allows you to clean up stuff like tinymce before the actual validation is done. Until it is released you can put that yourself in the jQuery.validator.prototype.form method, just at the start call this.settings.beforeValidation().
@Jose: I guess that would work. It makes titles utterly useless for the default methods, but considering the problems, that should be acceptable.
@Hanif: The problem is pretty clear and was caused by a change in jQuery 1.1.4. It doesn’t accept invalid XHTML anymore (in IE). As Chris points out, the fix is to add a closing slash to the error label creation. That fix is already included in the latest revision.
@Rider: jQuery’s expression supports OR using commas, eg. “#required:checked,#optional:checked” returns “true” if either #required or #optional is checked. Having an AND would help a ton in this scenario, though currently there is no way to define that. I’ll keep that in mind. Either I’ll add a custom expression to the validation plugin or maybe we can add something to jQuery itself. Until then you have to fall back to a function that implements the AND logic.
@John: Do you need an AJAX submit or just a plain submit with validation? In the latter case: Don’t specify a submitHandler at all.
@Marvin: Yes. Please give the latest revision a try.
First I want to thank you for the awesome plugin Jorn.
I am posting here because I am dynamically creating rows of inputs. I can create them just fine and even create rules for them and then validate them and it works great. However I have also created a button to remove them one at a time and when I do it will not let me continue to the next page. This is obviously because the rule still exists, so I tried nulling those indexes in the array, no luck. I have tried iterating through the array, copying the indexes and their data to a temporary array while excluding the ones I don’t want to keep and then setting the rules array equal to that temp array and still no luck.
I was hoping you would have some suggestions as to how I can remove the dynamically created rules of the last cloned object and still be able to validate what is left of the entire form.
Thanks,
Patrick
More on my previous posting…
I would like to add that I have tried using delete to remove the object property (I know, I know, before I was treating like an array but now I am treating it like an object. I am new to javascript). The delete command successfully removes it from the rules object, but the form will not submit successfully.
If I add the new rows of inputs but don’t remove any and fill it out correctly then it lets me send the form. This part is a real head scratcher. Thanks for the help!
Thanks,
Patrick
Just tried the latest revision to try to fix the IE issue above but still no luck. I tried the revision dated 2007-09-25. I still get the same error: “Object doesn’t support this property or method”. Is there something else I can try and do you know the specific reason it gets this message?
Thanks,
Marvin
I want to apologize. I made a bonehead mistake and forgot to refresh the validator after removing the rules. That fixed it. Sorry and thanks for the great plugin.
-Patrick
Hi Jörn,
Please see my post from 29. September 2007 |15:51. Any ideas of what I could do?
Hi Jorn,
I discovered a very weird bug in IE. When you add a new dynamic field in your form in IE, it will validate for the first new dynamic field. Then after that when you add a few more child, it wont validate properly for the newly created fields after the first one being validated. It happens even in your demo. Can you take a look at it ? It’s quite urgent, as most of my clients are using IE browser.
Thanks
Please ignore my previous post. It’s jQuery’s incompatibility issue.
Hi Jörn,
I discoverd that the newest release from you doesn’t work. i used latest metadata rev 3554 and the latest validate plugin rev 3607.
Firebug says jQuery(element).metadata is not a function in line 895 of the validation plugin.
Thanks for the great work of yours!
Hi all,
I have rules defined like
rules: {
postcode: {
ukpostcode:true,
zipcode:false
}
}
using custom methods; but both of them try to validate. What could be wrong? (in fact I have functions that return booleans).
Thanks
Now I’m getting the error “$.meta has no properties” when it encounters the line “$.meta.setType(“attr”, “validate”);”. any ideas why this is happening?
Ok, hopefully todays post won’t be another mistake on my part. I am trying to display the errors in a custom container and everything is working almost perfectly. Except I have notice that when it builds the list of errors to print to the screen, it brings the container into view (good), it lists the number of errors (fantastic), but then next to each listing number the actual error messages are hidden from view.
The messages are getting a style = display:none; attribute from the defaultShowErrors() function. Even weirder is the fact that if you click anywhere on the page at that point it brings only the first error into view. Multiple clicks to nothing else. Also above my error list I used your example to print the number of errors. Before the click I see the correct number of errors (lets say
then after the click it says only 1 error has been found.
Now I can brute force the rest of the messages to display by doing a search in that container for all elements with the tag and then change the attribute style to display: inline. However they still don’t show up until that extra click event happens. So for my users to see the errors they have to click submit, see the error container, then click again anywhere on the screen.
I looked through your plugin and I don’t see why it is creating and waiting for a click event before completing processing during validation. I am probably missing something so I am not going to jump to any conclusions. Any suggestions? Thank you for your time!
Sincerely,
Patrick T
Ok I figured out the $.meta error I was getting. In the newest version in the repository, it requires the use of $.metdata instead. That worked.
To fix my problem with IE – more specifically IE 6, I needed to use the jquery.validate.min.js file. When I used the jquery.validate.pck.js or jquery.validate.js file, it gave me the “Object doesn’t support this property or method”. That error was gone when I siwtched to the “min” file. So you might want to check out why there’s taht discrepancy. Otherwise, IE 7 and Firefox work with the other files.
@Marvin: Looks like you didn’t include the metadata plugin. Its linked above in the Dependencies section.
@David: You can use the errorPlacement-option for the positioning. See the custom methods demo for an example.
By defining appropiate CSS rules you can prevent that the input is “marked”, eg. limit any .error rules to labels: label.error { color: red; …}.
@Alex: Paul McLanhan has a new metadata plugin in the works, and I’m already using that in the latest validation plugin version. Give the one in the validate-folder a try.
Though currently it looks like the viewer von dev.jquery.com is out-of-sync. I’ve uploaded the latest revision until that is resolved.
@Roland: Can you explain what the exact problem was?
@Stan: The plugin uses regular JavaScript objects to define rules, but in most cases, the only the key is necessary, not the value. In other words, it doesn’t matter if you specify true or false, as long as the key (the rule) is present, it gets validated.
@Pjerky: Could you post a test page for that issue? That would help a lot debugging the problem.
Here’s a quick function that will verify that fields match (password fields, etc)
jQuery.validator.addMethod(“matches”, function(value, element, param) {
if($(‘#’ + param).val() != $(element).val())
return false;
return true;
}, “Please ensure that your verification fields match.”);
To use this, in your rules, just have something like:
‘passwordVerify’: { matches: ‘password’ }
Thanks Jörn but that’s what I was affraid of. Is there a way to do otherwise as with ‘required’ method from your example at the top of this page:
required: function() {
return $(“#age”).val()
Hi Jörn,
the errors stopped with the latest jquery (subversion) and your latest jquery.validation.js and the latest jquery.metadata.js. however if the jquery.validation.min or pack is used it still fires up the error that metadata is no funktion.
thx for your help.
Ok, since the file is large I have posted a stripped down html sample on my subdomain. It has everything needed to run the form the way I designed it.
The link is: http://pt-stable.ttishipdirect.com/spotquote_sample.html
Thanks for your time,
Patrick
Many thanks !
the OR logic, with commas, works well …
Hi Jörn,
I moved the logic to the added method and more or less happy (the only drawback I can’t have a separate error message for previously two different regexp metheds.
Found something else from example:
$(“#myform”).validate({
errorContainer: $(“#messageBox1, #messageBox2″),
errorLabelContainer: $(“#messageBox1 ul”),
wrapper: “li”,
});
when an error is highlighted and fixed, the error message disappeares but the heading The are errors in your form! stays! Do you know why and how can I fix it?
Thank you,
Stan
@Chris: Thanks, but that is nearly identical to the default equalsTo method. It accepts a jQuery selector though, giving you a bit more flexibility.
@Stan: I experimented with hiding the complete error container when validating a single element – instead of only on submit, as it is currently implemented. It was rather annoying, because the container tended to keep flashing on a single keypress.
In case you want to give a try: Replacing the call to this.prepareElement() with this.prepareForm() in the element-method should be enough.
@Alex: Thanks for the report. I should’ve updated those. Currently I’m having difficulties with the build script, something is broken there. Until I figure that out, you could just use Dean Edward’s packer directly.
I have a bit of a strange one: I have a table that consists of input fields, and I have a button to create a new row by cloning the bottom row of the table. The row that’s cloned has columns that look like:
but it appears that the metadata is not read because those new rows don’t get validated. and since the id of the new fields gets incremented everytime a new row is created, i’m not sure how to specify that these new rows need to be validated.
Any ideas on how to deal with this?
I noticed Dean mentioned the two submit button issue and the answer was to give the Cancel submit a class=”cancel”. I’ve done that and it still doesn’t work. Removing the Cancel button all together makes everything work. Is there something else I may be missing?
Hi,
Jorn: Exist a way to display the errors inline and in a separate box together ( for the same validation event) ??
I tried but did not get it.
So a tried a workaround:
$(document).ready(function(){
$(‘#something’).validate({
errorElement:’p',
errorClass:’errorField’,
errorPlacement: function(error, element) {
var isclass = element.attr(‘id’);
error.insertBefore( element.prev());
element.parent().addClass(‘error’);
var link = ‘‘ + error.text() + ‘‘;
$(‘#errorMsg ol’).append(link);
},
success: function(label){
label.parent().removeClass(‘error’);
}
});
});
The idea is to catch from success the the label.text(), compare with the element in the #errorMsg box where have been previusly added and hide the matched one.
My preoblem is the label argument passed by success…
label.text() do not retrn nothing and I even cannot add or remove classes.
How get the text from ‘label’….maybe I do not get what is label. Should be the jQuery element creaeted to display the error on validation….or am I wrong???
Thanks
Andrea
Hi,
I noted that using the errorPlacement when I insert text in a required field after that the validation has failed the event run for every carachter I write and the (now) empty error element is continuosly inserted in the dom.
Is that normal???
Code is this:
$(‘#something’).validate({
errorElement:’p',
errorClass:’errorField’,
errorPlacement: function(error, element) {
error.insertBefore( element.prev());
element.parent().addClass(‘error’);
},
success: function(label){
label.removeClass(‘errorField’);
label.parent().removeClass(‘error’);
}
});
Thanks
Andrea
@Joe: You need to call the validator’s refresh() method after adding new inputs. The latest revision allows you to pass those new elements directly to the refresh()-method, allowing you to refresh only new elements.
@Gregg: Can you post a test page?
@Andrea: I’m not quite sure what you are trying to achieve. A test page could help a lot.
I am trying to display errors in a custom container, however I have notice that when it builds the list of errors to print to the screen, it brings the container into view, then it lists the number of errors, but then next to each listing number the actual error messages are hidden from view.
The messages are getting a style = display:none; attribute from the defaultShowErrors() function. Even weirder is the fact that if you click anywhere on the page at that point it brings only the first error into view. Multiple clicks do nothing else. Also above my error list I used your example to print the number of errors. Before the click I see the correct number of errors (lets say then after the click it says only 1 error has been found.
Now I can brute force the rest of the messages to display by doing a search in that container for all elements with the tag and then change the attribute style to display: inline. However they still don’t show up until that extra click event happens. So for my users to see the errors they have to click submit, see the error container, then click again anywhere on the screen.
I looked through your plugin and I don’t see why it is creating and waiting for a click event before completing processing during validation. I am probably missing something so I am not going to jump to any conclusions. Any suggestions? Thank you for your time!
Here is the validator settings part of the script, m