An Introduction to jQuery and Form Validation

This post is more than 2 years old.

Last week I was performing a security review on a charity's web site (because that's how I roll, I'm nice like that) when I noticed they were using a jQuery plugin for forms validation. This was something I had not yet looked at in the jQuery world so I decided I'd take a closer look this weekend. I have to admit that I'm in awe over what I've found. I've avoided client side form validation for a long time (and I'll talk more about why in a minute) but I see no reason to do so anymore. What follows is a brief introduction into what I've learned. I'll be blogging a bit more on this topic later in the week with some more advanced examples.

First, the nitty gritty. All of the code I'm going to talk about today uses a jQuery plugin. This is not something built into the main jQuery file. The plugin has the wonderfully simple name of Validation and may be found here. It was written by a member of the jQuery team, Joern Zaefferer. Documentation may be found here.

The plugin works in two main ways. You can either use various CSS classes and attributes in your HTML to 'flag' fields for validation or use JavaScript to explicitly define validation rules and behavior. I'll be focusing on the 'inline' version for this blog entry. It is the simplest and most direct way to do validation, but only scratches the surface of what the plugin supports. (And to be clear - even in the 'inline' version I'll use a bit of JavaScript.) Let me start with a sample (ripped from the jQuery docs) to give you an idea of how easy this plugin makes validation.

<html>

<head> <script src="/jquery/jquery.js"></script> <script src="/jquery/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#commentForm").validate(); }); </script> </head>

<body>

<form id="commentForm" method="get" action=""> <fieldset> <legend>A simple comment form with submit validation and default messages</legend> <p> <label for="cname">Name</label> <em></em><input id="cname" name="name" size="25" class="required" /> </p> <p> <label for="cemail">E-Mail</label> <em></em><input id="cemail" name="email" size="25" class="required email" /> </p> <p> <label for="ccomment">Your comment</label> <em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form>

</body> </html>

So going down the code line by line, ignoring HTML we don't care about, make note that we include the plugin right after we load the main jQuery library. The script block will contain the only line of JavaScript we need for the entire validation:

$("#commentForm").validate();

This means: "Find the form with the id commentForm and turn on validation."

And that's it. Seriously. I mean, they couldn't make that any simpler unless they walked over to your house, wrote the code for you while simultaneously pouring you a cup of coffee. How does the validation work? Notice that each of my form fields has a class attribute. The name and comment form fields each have a class of required while email has a class of required and email. You can see this in action here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test0.html

If you load up the form and immediately hit the submit button, notice that all 3 form fields will have an error message added next to them. Enter a name and a comment, but then try putting in a bad email address. Notice how the error changes? That's slick. As you can probably guess, you could change the error messages but in my tests with simple inline validation, the error messages simply just plain worked and worked well!

So if 'email' flags a field as an email address, you can probably guess that there are other options as well. I'll throw in my one main complaint here and that is the documentation doesn't clearly talk about how to work with this inline version of the validation. I asked about this on the jQuery listserv and this is what I found. If you view the list of built in methods (http://docs.jquery.com/Plugins/Validation#List_of_built-in_Validation_methods), you can translate each of these built in methods to an 'inline' version by following these rules:

a) If the validation method takes no arguments, simply add it to the class attribute.

b) If the validation method takes an argument, add it as an argument to the tag itself.

In English, what does that mean? Well for simple checks like url, date, you can do this:

<p> <label for="cbd">Birthday</label> <em>*</em><input id="cbd" name="cbd" size="25" class="required date" /> </p> <p> <label for="curl">URL</label> <em> </em><input id="curl" name="url" size="25" class="url" value="" /> </p>

I've added two new form fields. One for birthdate and one for URL. The date validation worked surprisingly well. If there is one thing I've learned about JavaScript and dates is... well, I hate it. Period. So I was pleasantly surprised to see it nicely handle "April 8, 1973" as well as "4/8/73" and "4/8/1973". Also note that my URL field does not have required set. This means that I can leave the field blank, but if I type anything in, it has to be a valid URL.

But what about validation methods that take arguments? You can add these to your HTML as additional attributes. So for example:

<p> <label for="cname">Name</label> <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" /> </p> <p> <label for="cage">Age</label> <em>*</em><input id="cage" name="cage" size="4" class="required number" min="1" max="100" /> </p>

In the first field above I used minlength to specify that the name must be at least two characters. In the second field I specified a min and max value for age. Remember how I said the built in error messages were nicely done? When you try the demo (URL coming up in a second) notice that the error message will correctly handle input both below 1 and over 100.

Let's look at another quick example:

<p> <label for="cfu">Bio Upload</label> <em>*</em><input type="file" id="cfu" name="cfu" size="25" class="required" value="" accept="pdf" /> </p>

This creates a required file upload field where only PDFs are allowed. Obviously it can only check the extension, but as I said, pretty darn easy, isn't it?

You can view this demo here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test1.html

Note too that the errors are styled a bit nicer. I added this to the HTML:

<style type="text/css"> label.error { float: none; color: red; padding-left: .5em; vertical-align: top; font-weight:bold} </style>

I found this in a demo (by this I mean the use of label.error) but I don't remember seeing it in the documentation anywhere.

So... what next? As I mentioned earlier in the blog entry there is a lot more that this plugin supports if you are up to writing a bit more JavaScript. I've got a few more blog entries in mind over the week so please stay tuned. Finally, let me get on my soapbox for a minute. This stuff is all very cool. It's all very simple. It just plain works. You must remember, however, that no amount of client side validation can replace server side validation. I can disable JavaScript in Firefox with a few mouse clicks so you must always ensure you do proper server side validation before even considering adding client side validation. (If folks want, I can show an example of that as well.)

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Neil Bailey posted on 2/10/2009 at 2:57 AM

We ALWAYS do as much client-side validation as possible, negating the need for multiple AJAX calls to the server. JS has come a long, long way since the days of mouse-rollovers and status bar messages :)

Comment 2 by Rick Mason posted on 2/10/2009 at 4:04 AM

Ray,

The date validation isn't bullet proof. Try entering 5/22//52 and it doesn't catch it. Believe me that's a very common error in a date field.

Comment 3 by Raymond Camden posted on 2/10/2009 at 4:11 AM

I just did a quick test w/ the native JavaScript Date() constructor. When you pass M/D/Y and duplicate the /, it simply ignores it. So it treats //// as /, which is probably a fair thing to do. So I think this is more a 'looseness' in JS than jQuery.

Comment 4 by Gabe posted on 2/10/2009 at 4:49 AM

I had to build a huge, 300+ element form with multiple levels of validation, and the jQuery form validation was a life savior. The only problem I had was IE6 support. Without multiple ondocument loads, certain things were ignored in IE6. Of course, worked greatin every other browser.

Comment 5 by Gabe posted on 2/10/2009 at 5:05 AM

Sorry, shouldn't have tried writing that last post on the iPhone on the couch. In IE6, the document.ready function didn't work in every case, because IE6 had not finished rendering the page (completely). I had to add something like:

setTimeout(function() {
doSomething();
}, 500);

using the setTimeOut option for each validation in the document.

Comment 6 by todd sharp posted on 2/10/2009 at 5:06 AM

Am I the only one who realized that you slipped your birthday in to this post?

Comment 7 by denny posted on 2/10/2009 at 5:09 AM

Heh. I'm a broken record, but Dojo has /excellent/ validation stuff.

And Dojo is geared for internationalization, and accessibility.

jQuery is getting there, but I love how dojo made it a huge part of the whole deal.

Probably un-needed in the grand scheme of things, I mean, who really needs multiple languages or accessibility? -- But still, I really think it's swell that Dojo made it an important part of their overall approach.

I just saw a blog post on using jQuery to do server-side validation, which looked interesting. If I come across it again I'll send you the link.

Sorry to keep saying "check out dojo", but I keep seeing people sorta re-inventing the wheel-- while leaving some pretty cool spokes off, as it were.

Guess I'm a fanboy of sorts. Heh. I'm down with that.

:-)

Comment 8 by shag posted on 2/10/2009 at 5:18 AM

Even our UK friends will like this as the date accepts European date formats (22/5/09).

Comment 9 by Scott Stroz posted on 2/10/2009 at 5:20 AM

Does the addition of the extra 'arguments' break HTML/XHTML validation?

Comment 10 by Brian Swartzfager posted on 2/10/2009 at 5:22 AM

When it comes to dates, you're probably better off giving the user some sort of date picker so you can limit the number of possible errors the user can make. Fortunately, there are a number of date picker plugins for jQuery. :)

I have to agree with Rick, though: the date validation code in this Validation plugin has room for improvement. It failed my favorite date validation test, which is to see if it tags a non-existent date like Feb. 31 as being wrong. That's something a date picker can prevent merely by not giving you the option of picking that date.

Comment 11 by denny posted on 2/10/2009 at 5:29 AM

@Scott

Check this out: http://dojotoolkit.org/foru...

Basically, you can use pure JS or CSS if you're concerned with html validation, whatever the JS library.

Depends on how you want things to degrade and whatnot, too.

Comment 12 by Raymond Camden posted on 2/10/2009 at 5:34 AM

@Scott Stroz: If it does break HTML/XHTML validation, remember that this style ('inline', which is a term I picked and may not be the best term) is _optional_. Most examples I saw did not use this. I liked it though and that's why I focused on it for this entry. If you are concerned about HTML/XHTML validation you would simply not use that style (if it does indeed break). The good news is that the 'harder' way isn't that much harder really. (Next blog entry later tonight/tomorrow.)

@ToddSharp: Did I really? Hmmm, isn't that interesting. I'll have to include a link to the wishlist in the next example. ;)

@Denny: DOJO - I can only learn one thing at a time! ;)

@BrianS: Yep, when I was playing with the UI stuff last week or so, I did see the date picker and thought it was rather nice!

Comment 13 by Scott Stroz posted on 2/10/2009 at 5:35 AM

Wasn't worried as much as I was curious.

Comment 14 by existdissolve posted on 2/10/2009 at 7:46 AM

@ray--

I've used Spry's validation tools a little--I like how simple they are, but the amount of markup (and JS includes) required is a bit overwhelming.

I like that this spits out error messages for you--the less typing, the better :)

Hopefully, Spry will steal some of the nice things here and implement them into future releases.

Comment 15 by Raymond Camden posted on 2/10/2009 at 7:48 AM

Yeah, I don't think I stressed this enough, but the built in error messages are DARN nice and very intelligent.

Comment 16 by Jeff Self posted on 2/10/2009 at 8:24 AM

Ray,

Any way to set custom patterns? For instance, I'm working on a single field form that accepts either a 13 digit number or a 8 digit number. Anything else should be invalid. I've just started playing with jquery in the last week and I find it pretty cool.

Comment 17 by Paul Sturm posted on 2/10/2009 at 8:30 AM

Ray, I started using this about 2 months ago and I found the same issue - the inline docs leave something to be desired. I didn't contact anyone, I'm the kind to waste too much time on something instead of asking for help. I'd bet your way is quicker!

I've slipped the class fields into my code generator that builds my forms for a given database table. Then all I've got to do is create my $(document).ready()

Very unobtrusive. I should have guessed this was built by a jQuery team member since it is so 'elegant'.

By the way, your post form won't allow for email addresses with a '+' in it - as if that was invalid. I'll have to check and see if THIS plugin will allow it...

Comment 18 by Raymond Camden posted on 2/10/2009 at 8:48 AM

@Jeff Self: Yes, you can do custom validation. I'll show an example of that around my 3rd blog entry.

@Paul Sturm: Sorry about that. That is a bug fixed in BlogCFC, but my blog install here is a bit out of date.

Comment 19 by denny posted on 2/10/2009 at 8:54 AM

@Jeff:

Extending jQuery validation:

http://tinyurl.com/5onkka

You'll be wanting to look at the regular expression stuff.

Something like this:

$.validator.addMethod('eightOr13', function (value) {
return /^((\d{13})|(\d{8}))$/.test(value);
}, 'Please enter a valid 8 or 13 digit code.');

I still like dojo's approach better tho. :-)P

@Ray: time is an interesting concept. :-)

Comment 20 by Brad Wood posted on 2/10/2009 at 9:12 AM

We are using the jQuery validation plug-in. It does make 95% of your basic validation tasks easy. My main problem with it was that the "remote" validation type that lets you use an ajax call to get a response from the server only lets you pass back true or false. You aren't allowed to use a custom message based off of something random like "That discount code expired on January 1st"

Luckily, it's all open source so it was an easy addition.

Comment 21 by Raymond Camden posted on 2/10/2009 at 9:17 AM

@Brad Wood: Hush, you are giving away some of the cool things I want to bring up. ;) The Ajax validation part is probably the slickest part of the package. I can't wait to demo it.

Comment 22 by Sebastiaan posted on 2/10/2009 at 2:19 PM

Hi Ray, I was reading the comments hoping someone would address the Ajax stuff. I currently use a similar validation-framework (Prototype 1.5 - an older version, but nonetheless it works like a charm), but haven't been able to figure out how it can reset the validations when NOT using a submit button. Hence using an AJAX call in a button using onclick to submit the form. Currently I'm using a CFGRID (it's residing in a cflayoutarea with tabs) and in the other I have a form that's submitting NEW data to the grid. But the validation only works when I'm leaving the field (onblur) and not on the button. If I submit it all the validation messages don't disappear and when using the form a second time (adding another) the validation doesn't work at all. Of course no problems at all when replacing the on-click action button with a submit button.

Come up with the preso/demo ;-)

Comment 23 by Seb Duggan posted on 2/10/2009 at 3:45 PM

Yes, the extra arguments break HTML validation.

I prefer to use tha alternate method: if you also add the jQuery metadata plugin - http://plugins.jquery.com/p... - you can do something like this:

<p>
<label for="cage">Age</label>
<em>*</em><input id="cage" name="cage" size="4" class="required number {min:1,max:100}" />
</p>

Comment 24 by Jörn Zaefferer posted on 2/10/2009 at 4:25 PM

About the date validation issues: This is certainly a weak feature of the plugin, but one that seemed to work well most of the time, that is, I rarely ever see any questions or requests on the date methods. If there were more requests, I'd consider integrating the datejs library (http://www.datejs.com/).

About Gabe's issue in IE6 and document-ready: Have you tried placing your doSomething()-call in a script block just before the closing body-tag?

About localization: The plugin has english as the default language, but is bundled with 17 localizations (mostly contributions from other users).

About accessibility: The plugin uses labels with the correct for-attribute for the error messages, so a screenreader should be able to link the error-label to the associated input.

@Brad Wood: Would you mind sharing your addition?

Comment 25 by Jeff Horne posted on 2/10/2009 at 6:59 PM

I've started using jquery recently and have found it very promising. I recently integrated a datepicker into our customer website and skinned it with ThemeRoller from the <a href="http://ui.jquery.com/home" target="_blank">jquery UI site</a>. I was then bitten by the IE6 unable to handle a png problem. It's always something with IE6.

Unfortunately, most of the examples I find are with php and asp so I have to integrate it into cfm myself. Your ideas are very, very helpful, Ray. My latest adventure is to place a file upload form into a jquery accordion panel that stays in the panel after the upload. It's slow going.

Comment 26 by Jeff Horne posted on 2/10/2009 at 7:06 PM

Oops. Sorry about the link in my last post.

Comment 27 by Raymond Camden posted on 2/10/2009 at 7:10 PM

No worries Jeff Home. I keep meaning to add text to the comment form mentioning that URLs are auto linked and HTML is escaped.

Comment 28 by Tony Nelson posted on 2/10/2009 at 7:55 PM

I've recently started playing with jQuery afters years with Prototype and have found jQuery has some pretty elegant plugins compared to Prototype.

The inline validation seems convenient, but maybe not the most unobtrusive approach. If you think of validation as just another aspect of your application, having the validation rules (class="required" minlength="2") applied directly to the form fields isn't the best separation of concerns.

Granted the pragmatic side of me says this lightweight approach probably fits the need for most developers out there and that a more AOP-style validation engine, either database or XML driven, might be a little overkill.

Comment 29 by Raymond Camden posted on 2/10/2009 at 7:58 PM

@Tony: Working on the demos for the next post now. :)

Comment 30 by Lola LB posted on 2/10/2009 at 9:22 PM

Interesting. I like this better than the built-in cfform validation where you have popup windows. Somehow I find these popup windows rather irritating and not very attractive.

Comment 31 by Raymond Camden posted on 2/10/2009 at 9:25 PM

Agreed. Also, I tend to prefer errors on top of my form, not to the right of the fields, especially on short forms. This plugin allows for that and that will be in my demos later today.

Comment 32 by Neil Bailey posted on 2/10/2009 at 9:33 PM

My biggest problem w jQuery is that its ANOTHER freaking library that I have to learn and download to the client machine.

We currently use the EXTJS package, and while its not stoopid large, its not tiny.

Why can't there be a single package that does every freaking thing........... <piss and moan>

Comment 33 by Raymond Camden posted on 2/10/2009 at 9:36 PM

Since my return to JS (that sounds overly dramatic) I've found that the various JS libraries are much like the various server side languages we have.

Both PHP and CF support reading files, but they certainly do it different ways. Ditto for the JS frameworks out there.

It is important that you (and by you I mean either you as the sole developer or you and your organization) find the library that enables you to be the most productive. (Frankly I think client download isn't a huge concern. jQuery has compressed versions and I'm sure EXT does as well. Spry does for sure.)

Comment 34 by denny posted on 2/11/2009 at 6:23 AM

@Jörn: Sweet! I loves me some multi-language and accessibility. Scores some major points in my book. Might not hurt to add that info to the plugin page. I know most people don't care, but still.

@Everyone/anyone:
jQuery seems to be going for the bottom-up on localization and accessibility, vs. dojo's top-down. I can appreciate the logic, and I feel that the only way it will work, is if devs guide other devs in "the right way" to code this stuff.

Make a big deal about being multi-lingual, and accessible (in general)!
Or maybe don't. Evolution will take care of all of it, in the end, come to think of it. Eh. =]

@Ray & Niel: Dojo has had /everything/ and /anything/ that I've needed to do with JS. Just amazing stuff. The build system, various tools for working with other languages... just far-out, wonderful stuff. I like how things are organized (the sources)... the list goes on and on.

Course, javascript is a pretty freaky language in and of itself, and just about any "helper" lib can do nifty things for it, so... guess whatever floats your boat, as with anything.

Swell to hear that localization and accessibility have been thought of with this jQuery validation plugin. I don't know why I like that so much, but I do. =]

Comment 35 by Michael Williams posted on 2/11/2009 at 11:07 AM

I would like to see your take on server side validation. I don't think enough is written on that subject. Especially with regards to xss.

Comment 36 by Jose Galdamez posted on 2/13/2009 at 12:38 AM

The timing for this is great. I was going through the WACK book volume 1, and was loving the fact that you could have CF take care of client-side validation through the use of <cfform>. I was able to get <cfform> validation working in a snap on our testing server, but the minute I sent the files to production they stopped working. The code was fine. I believe that our hosting provider at the university has to be mapping something improperly so that the JavaScript files aren't being loaded properly (e.g. /CFIDE/).

That means we can't rely on <cfform> for any of its JS or AJAX-related features. Bummer!

After shopping around, I found jQuery to be a nice alternative. These demos make it seem even more enticing. In a way, the examples here are better than what one would get from <cfform> because you don't get the annoying alert() window. The error messages are much more friendly.

Comment 37 by denny posted on 2/13/2009 at 2:55 AM

@Jose

You can use the "scriptsrc" cfform attribute to specify a different directory to pull the JS and stuff from, bypassing a call to your IT department.

HIH

Comment 38 by Chris posted on 2/16/2009 at 4:39 PM

Ray, this is perfect. I'm working on a site with some forms and I have to use validation. Sharpening my teeth with jquery at the same time.

I couldn't figure out from the documentation for the validation plug in how to make a text input field required when they choose a specific drop down box.

Basically I have a "how did you hear from us" drop down. If they choose "OTHER" I need to make the "OTHER" input field required.

If this is in the documentation, I'm sure I missed it for sure. Maybe a link to the page?

Thanks!

Comment 39 by Raymond Camden posted on 2/16/2009 at 5:15 PM

The second entry in this series shows an example of 'if you pick a checkbox, you must enter so and so field', but this is not exactly what you mean. I'll do some research and get back to you. Most likely it will be a 'depends' type thing, which I saw an example of before and need a bit more coffee to figure out.

Comment 40 by Raymond Camden posted on 2/16/2009 at 5:28 PM

The solution is here. I'm about to get my kids up for school and do other things to prep for work so I'll be off the grid for about 1.5 hours. But I can whip up a quick demo when I get back.

Comment 41 by Raymond Camden posted on 2/16/2009 at 7:43 PM
Comment 42 by Prabhjot singh posted on 4/3/2009 at 10:19 AM

Hi there,

Iam new to ASP.NET and jquery, i implemented the above written code in my .aspx pages. I have added the .js files onto the page. Now, whenever i run my project i get an error "jquery is undefined". I really don't know how to move forward. any help!!!

Comment 43 by Raymond Camden posted on 4/3/2009 at 3:32 PM

Did you download the jQuery file itself?

Comment 44 by prabhjot singh posted on 4/3/2009 at 4:23 PM

yes sir, i did. i downloaded the plugin aswell. i created a new folder in my site by the name "js" and have put in the pluggin aswell as the jquery file. But still no results. i have a feeling that iam goin wrong somewhere.

Comment 45 by Raymond Camden posted on 4/3/2009 at 5:28 PM

Are you sure jQuery is loading right? In other words, if your HTML does:

<script src="/js/jquery.js"></script>

Is that the right path to the jquery folder? Does Firebug confirm the script has loaded?

Comment 46 by prabhjot singh posted on 4/4/2009 at 10:18 AM

hey, thanks for your help. It seems that the jquery files are loading pretty well, but now the error which it shows is something like this:

$("#form1").validate(); is undefined.

The code which i have written is as follows:

<script src="jquery.js" type="text/javascript"></script>

<script src="jquery.validate.pack.js" type="text/javascript"></script>

<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate();
});

</script>

and then the form validations in the body tag. What more i have to do??

Regards
Prabhjot Singh

Comment 47 by Raymond Camden posted on 4/4/2009 at 6:00 PM

This means the validation plugin isn't being found. Do you see the script src pointing to it? You need to ensure that is the right location for the file.

Comment 48 by prabhjot singh posted on 4/6/2009 at 9:14 AM

Hi, iam getting an error when i run my program on firebug

key is undefined
[Break on this error] var parts = key.split(".");

This error is pointing to jquery.js file. When i open the description i get this

data()()jquery.js (line 1355)
data()(input#cname.required)jquery.v...lidate.js (line 795)
rules()(input#cname.required)jquery.v...lidate.js (line 771)
(?)()()jquery.v...lidate.js (line 609)
(?)()()jquery.js (line 353)
grep()(Object length=3 0=input#cname.required, function(), undefined)jquery.js (line 1129)
filter()(function())jquery.js (line 352)
refresh()()jquery.v...lidate.js (line 605)
validator()(undefined, form#form1)jquery.v...lidate.js (line 397)
validate()(undefined)jquery.v...lidate.js (line 245)
(?)()()index.aspx (line 16)
(?)()()jquery.js (line 2905)
each()([function(), function()], function(), undefined)jquery.js (line 690)
ready()()jquery.js (line 2904)
(?)()()jquery.js (line 2929)
[Break on this error] var parts = key.split(".");

I have written down the same code as u. What next should i do??

Regards
prabhjot singh

Comment 49 by prabhjot singh posted on 4/6/2009 at 1:21 PM

hey Ray,

Everything is working just fine, Thanks for your help. Iam so happy

Comment 50 by prabhjot singh posted on 4/6/2009 at 3:11 PM

hi, can ia add my own functions in jquery file and make them work like all other functions??? what i have done is,

i have to validate my first name and the last name field in such a way that no alpha-numeric character is entered. The "required" is working fine, but what about the other thing like i have mentioned. I tried by putting in a new function in jquery.js but it did'nt work. So, is it possible??

Regards
Prabhjot singh

Comment 51 by Raymond Camden posted on 4/7/2009 at 2:00 AM

You don't want to modify jQuery.js. Instead, you want to look at the plugin architecture:

http://docs.jquery.com/Plug...

Comment 52 by Trevor posted on 4/16/2009 at 1:30 AM

Do you know if you can do a cross-domain option on this like you can with the $.ajax method? I've got what I want with straight-up jQuery, but turning it into something validator can deal with has been difficult. Here's the Pastie of my attempt to add a method to validator to accomplish this:

http://pastie.org/447779

-TR

Comment 53 by adnan posted on 6/8/2009 at 8:59 PM

Hi,

Thanks for sharing your ideas. But like others I also love the Spry validation of dreamweaver because of its ease of use and modifications. I can simple add the spry validation using mouse clicks. And I found a way for using the Spry validation of dreamweaver with jQuery ajax form submit here: http://abcoder.com/javascri...

Comment 54 by Ben Lopez posted on 6/12/2009 at 8:01 PM

Ray, whenever I try to solve a problem with ColdFusion and I see you have a tutorial on it, that is the first place I go. I wasn't expecting to see your name on a jQuery issue. But, clicked this link when I saw your name and low and behold I found the answer.

I could not get the required class to work on a file upload. I was using the recommended mime-type for the accept attribute "image/jpeg". When I changed it to accept="jpg" ... problem solved.

Thanks for posting this tutorial. I look forward in seeing more on jQuery from you.

I'm with you on learning one thing at a time. Unfortunately, for me I have a job offer and they are using DoJo...I understand that the 2 frameworks can will not conflict.

Thanks again Ray.

Comment 55 by Raymond Camden posted on 6/12/2009 at 8:11 PM

Thanks for the kind words, Ben. I've been doing jQuery a lot lately. Did you know I blog on InsideRIA now? I do most of my jQuery stuff there, but will do jQuery/CF stuff here. As for jpeg vs jpg - I run into that a lot as well.

Dojo: Yep, you can set up jQuery to use another 'root' instead of $. That way it won't conflict.

Comment 56 by Jay posted on 7/20/2009 at 11:03 AM

Great post Ray -- very helpful in setting up the plugin for the first timers.

I've had a few stints with the plugin myself -- But I was wondering if you knew of a way to 'highlight' the fieldset/div/table row (or another parent element) instead of adding a label with the error message inside. Know what I mean? So if the name textbox is empty, that entire div is highlighted, instead of the label action.

That's what I'm working on now. Would love your thoughts on it if possible.

Fantastic site btw -- keep up the great work :)

~Jay

Comment 57 by Raymond Camden posted on 7/20/2009 at 2:33 PM

Check out the demos page:

http://jquery.bassistance.d...

The demo with 'custom display' is close to what you want I believe.

Comment 58 by nemrod posted on 7/28/2009 at 4:52 AM

The javascript include files 404, the validation of the examples isn't working. Just a heads up :)

Comment 59 by Bill posted on 8/27/2009 at 4:31 PM

I am preparred to get flamed over this, so fill the gascans.
But I am new at this, that said:
Why do you prepend the fields with the letter "c"?
Is it a convention or part of the api for the validation plugin?
It seems to be kind of sporadic to the untrained eye.
I've attached your code below as an example.

<pre>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="cage">Age</label>
<em>*</em><input id="cage" name="cage" size="4" class="required number" min="1" max="100" />
</p>
</pre>

Thanks!

Comment 60 by Raymond Camden posted on 8/27/2009 at 4:34 PM

No good reason, outside of me thinking it was weird to have ID and NAME be the same, although I don't believe there is any need to have them different.

So... ignore/don't worry about/etc. :)

Comment 61 by Vesselin Obreshkov posted on 6/26/2010 at 4:25 AM

Isn't it considered bad (X)HTML though to have attributes such as "minlength" and such for the purpose of validation when jQuery allows you to specify all that in much more "standards friendly" way like this:

<code>
<script>
$().ready(function() {
$("#form).validate({
rules: {
name: "required",
number: {
required: true,
number: true
},
messages { ... }
}
});
});
</script>
</code>

This way you can also add custom error messages for each field in the same consistent way you define the rules for each field (would've been even nicer if they simply added a message attribute to the rules options).

Comment 62 by Raymond Camden posted on 6/28/2010 at 4:57 PM

@Vesselin: If you look at the other entries in this series (see Related Blog Entries above), you will see I discuss that.

Comment 63 by John posted on 12/1/2010 at 7:54 PM

Dear Raymond,

Thanks for the great article!
I'd like to put the labels on the right of text input fields and display the error messages under input fields.
Tried almost anything, but to no avail. :-(

Any help is greatly appreciated!

Comment 64 by Raymond Camden posted on 12/1/2010 at 9:43 PM

Initial quick response - for labels on the right - thats a purely HTML/CSS issue. You don't use jQuery for that.

Comment 65 by John posted on 12/1/2010 at 9:50 PM

Thanks for the quick response!
You're right and I know how to do it by simply displacing the <label> and <input> tags. But the problem is the label gets completely disordered when the error message appears.

Comment 66 by Raymond Camden posted on 12/2/2010 at 5:54 AM

Looking at the docs, http://docs.jquery.com/Plug..., it seems like the errorContainer specifies what is used for error messages. I'd look into that as a way of saying, 'put the errors here.'

Comment 67 by John posted on 12/2/2010 at 10:34 PM

More than what I expected -- So helpful! Thanks! :-)

Comment 68 by OnLine posted on 7/3/2011 at 11:40 AM

Hy,
For simple form, with two or three fields, i think is better to write yourself the validation code than including the entery Validation plugin.
Something like: if ($('elm').val().length == 0) { alert('message'); }
Or:
if($('elm').is(':checked')) { alert('message'); }

Comment 69 by Raymond Camden posted on 7/3/2011 at 4:58 PM

Well certainly - but most forms are not one or two fields. ;)

Comment 70 by kumar posted on 6/20/2012 at 3:26 AM

Thanks for the simple post

Comment 71 by 1 posted on 7/8/2012 at 6:42 PM

Your example only works onsumbit while theirs works after input why is that?

Comment 72 by Raymond Camden posted on 7/8/2012 at 6:46 PM

That's just how I liked it. This blog entry is a few years old but if I remember right, you can do either. It is up to you to decide when you want the validation to fire.