Yesterday I blogged about jQuery and form validation using the excellent Validation plugin by Joern Zaefferer. I demonstrated simple validation techniques using simple additions to your HTML and one line of JavaScript. In today's blog post I'm going to dig a bit deeper into the JavaScript API for the plugin and show more advanced examples of forms validation. As always, please remember that I'm still new to jQuery (and especially this plugin) so comments are welcome!
2
3 <head>
4 <script src="/jquery/jquery.js"></script>
5 <script src="/jquery/jquery.validate.js"></script>
6 <script>
7 $(document).ready(function(){
8 $("#commentForm").validate();
9 });
10 </script>
11 </head>
12
13 <body>
14
15 <form id="commentForm" method="get" action="">
16 <fieldset>
17 <legend>A simple comment form with submit validation and default messages</legend>
18 <p>
19 <label for="cname">Name</label>
20 <em>*</em><input id="cname" name="name" size="25" class="required" />
21 </p>
22 <p>
23 <label for="cemail">E-Mail</label>
24 <em>*</em><input id="cemail" name="email" size="25" class="required email" />
25 </p>
26 <p>
27 <label for="ccomment">Your comment</label>
28 <em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
29 </p>
30 <p>
31 <input class="submit" type="submit" value="Submit"/>
32 </p>
33 </fieldset>
34 </form>
35
36
37 </body>
38 </html>
2
3 <head>
4 <script src="/jquery/jquery.js"></script>
5 <script src="/jquery/jquery.validate.js"></script>
6 <script>
7 $(document).ready(function(){
8 $("#commentForm").validate({
9
10 rules: {
11 name: "required",
12 email: {
13 required: true,
14 email: true,
15 },
16 comment: "required"
17 }
18
19 });
20 });
21 </script>
22 </head>
23
24 <body>
25
26 <form id="commentForm" method="get" action="">
27 <fieldset>
28 <legend>A simple comment form with submit validation and default messages</legend>
29 <p>
30 <label for="cname">Name</label>
31 <em>*</em><input id="cname" name="name" size="25" />
32 </p>
33 <p>
34 <label for="cemail">E-Mail</label>
35 <em>*</em><input id="cemail" name="email" size="25" />
36 </p>
37 <p>
38 <label for="ccomment">Your comment</label>
39 <em>*</em><textarea id="ccomment" name="comment" cols="22" ></textarea>
40 </p>
41 <p>
42 <input class="submit" type="submit" value="Submit"/>
43 </p>
44 </fieldset>
45 </form>
46
47
48 </body>
49 </html>
2 <fieldset>
3 <legend>A simple comment form with submit validation and default messages</legend>
4 <p>
5 <label for="cname">Name</label>
6 <em>*</em><input id="cname" name="name" size="25" />
7 </p>
8 <p>
9 <label for="ccomment">Your comment</label>
10 <em>*</em><textarea id="ccomment" name="comment" cols="22" ></textarea>
11 </p>
12 <p>
13 <label for="csub">Subscribe to newsletter?</label>
14 <input type="checkbox" id="csub" name="csub" />
15 </p>
16
17 <p>
18 <label for="cemail">E-Mail</label>
19 <input id="cemail" name="email" size="25" />
20 </p>
21 <p>
22 <input class="submit" type="submit" value="Submit"/>
23 </p>
24 </fieldset>
25 </form>
2 name: "required",
3 email: {
4 required: "#csub:checked",
5 email: true,
6 },
7 comment: "required"
8 }
2 comment: "This is a comment form. Why in the heck would you leave the comment blank?",
3 email: {
4 required: "Dude, you want the newsletter, but you didn't enter an email address?",
5 email: "Email addresses are of the form user@host. Not yourRstupid."
6 },
7 name: {
8 required: "Stand up for your comments or go home.",
9 minlength: jQuery.format("You need to use at least {0} characters for your name.")
10 }
11 }
2 $("#commentForm").validate({
3
4 rules: {
5 name: {
6 required: true,
7 minlength: 2
8 },
9 email: {
10 required: "#csub:checked",
11 email: true,
12 },
13 comment: "required"
14 },
15 messages: {
16 comment: "This is a comment form. Why in the heck would you leave the comment blank?",
17 email: {
18 required: "Dude, you want the newsletter, but you didn't enter an email address?",
19 email: "Email addresses are of the form user@host. Not yourRstupid."
20 },
21 name: {
22 required: "Stand up for your comments or go home.",
23 minlength: jQuery.format("You need to use at least {0} characters for your name.")
24 }
25 }
26
27 });
28 });
2 return value.toLowerCase().indexOf("anonymous") != 0;
3 }, 'Do not hide behind the cover of anonymity');
2 required: true,
3 minlength: 2,
4 noanon: true
5 },
2
3 errorContainer: "#errorbox",
4 errorLabelContainer: "#errorbox ul",
5 wrapper: "li",
6 ... more code here ...
The display: none ensures the error box won't show up until the plugin turns it on. The yellow background ensures people remember that I shouldn't be allowed to design. Ever. Lastly I added this to my page:
1 <div id="errorbox"><ul></ul></div>
Put all together you can see this in action here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test32.html
That's it for this entry. I remain incredibly impressed by this plugin, and I think my next blog entry will really cement the Awesome Coolness that is jQuery. I'll be demonstrating an example that mixes client side validation along with server side checks.


Comment 1 written by Kumar on 10 February 2009, at 12:33 PM
The Form Validation stuff should be very useful in the future. Thanks Ray.
Comment 2 written by Raymond Camden on 10 February 2009, at 12:34 PM
Comment 3 written by Kumar on 10 February 2009, at 12:38 PM
Error Screen: http://i42.tinypic.com/foptea.jpg
Comment 4 written by Gabe on 10 February 2009, at 12:38 PM
Comment 5 written by Gabe on 10 February 2009, at 12:41 PM
rules: {
name: "required",
email: {
required: true,
email: true,
}, //this comma is throwing an exception
comment: "required"
},
Comment 6 written by Jim Priest on 10 February 2009, at 12:47 PM
http://ejohn.org/blog/server-side-javascript-with-...
Comment 7 written by Gabe on 10 February 2009, at 12:47 PM
rules: {
name: "required",
email: {
required: true,
email: true, //this comma is throwing an exception
},
comment: "required"
},
Comment 8 written by Dan G. Switzer, II on 10 February 2009, at 1:01 PM
Having had similar issues bite me in the past, I moved to placing my commas in front of additional lines, instead of after them. Since moving this this formatting style, I've avoided these types of errors.
Example:
p1
, p2
, p3
, p4
Comment 9 written by Michael Brennan-White on 10 February 2009, at 2:35 PM
http://www.accessify.com/tools-and-wizards/develop...
Comment 10 written by Raymond Camden on 10 February 2009, at 3:38 PM
Comment 11 written by Scott Stroz on 10 February 2009, at 5:05 PM
Comment 12 written by Garrett Johnson on 10 February 2009, at 5:11 PM
There are also many things functions you can pass into the validator as well for success and failure placement and responses. (not sure how this code will look below in this comment!)
$("#signupform").validate({
ignoreTitle: true,
onkeyup: false,
success: function(label){
label.addClass("success").fadeTo(3000,1).fadeOut('slow');
},
errorPlacement: function(error, element){
error.appendTo(element.next("span"));
},
meta: "validate"
});
Comment 13 written by brian on 10 February 2009, at 6:15 PM
Comment 14 written by Raymond Camden on 10 February 2009, at 7:55 PM
Comment 15 written by Raymond Camden on 10 February 2009, at 7:57 PM
http://www.mail-archive.com/jquery-en@googlegroups...
From the creator himself.
Comment 16 written by Jörn Zaefferer on 11 February 2009, at 4:44 PM
$.validator.addMethod("noanon", function(value) {
return this.optional(element) || value.toLowerCase().indexOf("anonymous") != 0;
}, 'Do not hide behind the cover of anonymity');
Otherwise the method would be always applied, even when the element isn't required.
@brian: Try class="requierd" minlength="2". <a href="http://docs.jquery.com/Plugins/Validation/Methods/...; works with inputs of type text, checkboxes and selects.
Comment 17 written by Raymond Camden on 11 February 2009, at 4:54 PM
Comment 18 written by brian on 11 February 2009, at 5:01 PM
Comment 19 written by Byron Raines on 21 February 2009, at 12:10 PM
This is my first try at JQuery validation and this has been very helpful. I do have one problem. I use Brian Kotek's FormUtilities, so I name my variables employee.fname, employee.lname, etc..
It looks like I can use the class="required" method but I can't specify employee.fname in the rules attribute. It throws an error From firebug:
missing : after property id
employee.fname: "required",\n
Is this correct. The only draw back is it looks like I can;t use custom messages with the "class=required" method.
Thanks again
Comment 20 written by Raymond Camden on 21 February 2009, at 3:36 PM
"name.moon": {
required: true,
minlength: 2
}
Comment 21 written by Byron Raines on 21 February 2009, at 3:55 PM
Thanks, Ray
Comment 22 written by cucumucz on 23 February 2009, at 2:34 AM
I am trying to implement a validation using this plugin, but failed to produce customized error messages. Lets say
we have there dates to compare ,
FromDate
ToDate
CurrentDate
FromDate <= ToDate
ToDate >= FromDate ( this can be achieved with above single validation also )
ToDate <= currentDate
hence my rules are:
rules:{
'fromDatelog': { beforeToDate:'toDatelog' },
'toDatelog': { afterFromDate:'fromDatelog' },
'toDatelog': { beforeToDate:'current_date'}
}
Now the problem is how can I produce a distinct message for each validation while I use the same validation rule
e.g
'fromDatelog': { beforeToDate:'toDatelog' },
I want message '"From Date" should be less than "To Date"'
and for
'toDatelog': { beforeToDate:'current_date'}
I want message '"To Date" should be less than "Current Date"'
any help ,suggestion will be appreciated.
Thanks in advance
cucumucz
Comment 23 written by Raymond Camden on 23 February 2009, at 7:58 AM
Comment 24 written by Mark S on 27 February 2009, at 6:26 PM
I need to keep the default error messages "field is required", but for certain fields I need to also pop up another message. I was wondering if this can be easily done with this jquery validation or do I have to write my own script?
Thanks in advance
Comment 25 written by Raymond Camden on 27 February 2009, at 6:38 PM
Comment 26 written by Mark S on 27 February 2009, at 6:42 PM
The problem is that the extra message has to be placed in a different area.. the extra message will need to be appended to an error box that appears away from the default message
Comment 27 written by Raymond Camden on 27 February 2009, at 6:44 PM
Make sense?
Comment 28 written by Mark S on 27 February 2009, at 8:18 PM
So, I will have to play with this
errorPlacement: function(error, element) {
}
Thanks for the help
Comment 29 written by mahendra on 20 March 2009, at 7:21 AM
please help me i am using following code for form validation
it work in FF fine ... but
it cannot work in IE6 and IE7
& also it cannot show any error
var design_validator = jQuery("#add_new_design").validate({
rules: {
design_title : { required: true },
design_comment : { required: true },
design_keywords : { required: true },
design_category : { required: true, noselect:true }
},
messages: {
design_title:{
required: "Please enter design title"
},
design_comment:{
required: "Please explain about your design"
},
design_keywords:{
required: "Please enter tag(s) for your design"
},
design_category:{
required: "Please select a category",
noselect: "Please select a category"
}
},
errorPlacement: function(error, element) {
error.appendTo(element.next().next());
},
submitHandler: function(data) {
//console.log(jQuery('#uploaded_default').val());
//console.log(jQuery('#uploaded_default_location').val());
},
// set this class to error-labels to indicate valid fields
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
}
});
.....please help me !!!!!
!!!!!! waiting for your replay!!!!!
Comment 30 written by Raymond Camden on 20 March 2009, at 5:21 PM
foo,
moo,
to
foo
,moo
If you look at my later blog entries in this series, I believe I switched to this format.
Comment 31 written by John on 2 April 2009, at 5:04 AM
Thanks for any help.
Comment 32 written by Raymond Camden on 2 April 2009, at 6:21 AM
Comment 33 written by John on 2 April 2009, at 6:37 AM
I didn't found the solution for this with checkboxes.
Thanks.
Comment 34 written by Raymond Camden on 2 April 2009, at 7:57 AM
I would check this out:
http://jquery.bassistance.de/validate/demo/
He has a demo just for checkboxes and selects.
Comment 35 written by John on 2 April 2009, at 9:35 AM
Thanks and great tutorial by the way.
john
Comment 36 written by Joe Devon on 13 May 2009, at 8:49 PM
('/^[a-z0-9\.\-_]+$/')
Any idea how to write that w/ JQuery Validator?
Comment 37 written by Raymond Camden on 14 May 2009, at 6:36 AM
Comment 38 written by José Luis on 14 May 2009, at 3:31 PM
I need to block or hide the submit button when the user click on it... I do a function to hide the button:
"function OcultaBoton(){
$('.bloquear_boton').hide();
}"
And I call in the form when it's submitted:
"<form action="index.php" method="post" id="DataForm" onsubmit="OcultaBoton();">"
that's work but when all the fields is not empty!!! if one of them is empty the button dissapear and the user didn't see the button again!!!
What can I do in this case?? if anyone have a idea!!!
Comment 39 written by Raymond Camden on 14 May 2009, at 3:42 PM
Comment 40 written by José Luis on 14 May 2009, at 3:51 PM
Comment 41 written by Raymond Camden on 14 May 2009, at 7:47 PM
Comment 42 written by Joe Hansen on 31 December 2009, at 12:31 PM
[Add Comment] [Subscribe to Comments]