Posted in jQuery | Posted on 02-10-2009 | 25,725 views
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!
In yesterday's blog entry, all of the validation I demonstrated made use of CSS or HTML attributes. So for example, to mark a name field as required and require a minimum of two characters, you would do:
To mark a field as requiring a valid URL, you would do:
And so on. While this works, you may want to have more complex validation. Some fields may only be required if you enable a checkbox. Some fields may have validation rules that don't fall into simple patterns. I also raved about how nice the default error messages are, but what if you don't like them? Luckily the plugin makes modifying all of these settings rather easy. Let's begin with a simple example.
First I'll repost the first code sample I shared yesterday. This uses inline CSS/HTML to specify validation settings.
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>
Now here is an exact copy that specifies the rules in JavaScript instead:
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>
Moving from the bottom up, note that I've removed all the validation related CSS items and HTML attributes. My validate() function now has a new argument: rules. The rules attribute (which can be used with inline code as well if you want to mix them up) creates a list of rules that the plugin will use when validating the form. For each rule you can specify a simple value, as I did with name, or specify a structure of more complex data, as I did with the email field. While this is a bit more complex (and takes up more lines because of my vertical spacing), notice now that the validation is removed from the HTML below and placed entirely within the JavaScript. This is a bit cleaner I think and for folks more comfortable with JavaScript this is definitely going to be the better option. You can view this version here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test02.html. As I said though, it should run exactly the same as the previous version.
Let's look at another modification now. Imagine the following form:
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>
I've added a new 'Subscribe' checkbox. If you want to subscribe to a newsletter, email should be required. I bet that's real difficult.
2 name: "required",
3 email: {
4 required: "#csub:checked",
5 email: true,
6 },
7 comment: "required"
8}
I've modified the email rule from required equals true to a check against the csub item and the checked property. Basically, "jQuery - go see if the form field with id csub has a checked property that is true". Maybe I'm crazy, but I don't even consider this as 'writing' JavaScript yet. All I've done is define some data! You can see this in action here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test3.html
So far I've just showed specifying rules. How about customized messages? Just as we can pass a rules object to the plugin we can also pass in a messages object as well. As an example:
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}
Each message is keyed to the rule and like rules itself, I can specify either a simple value (see the comment example) or a complex object. For emails we can specify a different message for each thing you fail. For name notice I made use of jQuery.format, a utility function supplied by the plugin (mostly sure it is a plugin function and not a core function) to allow for a dynamic message. If I were to change my minlength requirement for my rule from 2 to 5 I wouldn't have to worry about updating the error message. The complete constructor is below:
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});
A demo of this may be found here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test30.html
Alright, let's look at another example. What if we wanted to supply our own logic for validation. Scott Stroz asked this in a comment in yesterday's blog post. Once again, the plugin makes this rather simple. One way to handle this is by using the validator's addMethod function. The addMethod function allows you to add your own validation logic. Once done, you can apply this as a validation form in any rule. You can even build up a library of these and use it for multiple projects. Let's look at a simple example:
2 return value.toLowerCase().indexOf("anonymous") != 0;
3 }, 'Do not hide behind the cover of anonymity');
The addMethod function takes 3 arguments. A name, the logic to actually run, and lastly, the default message to use for failures. My use of the function above is rather simple - I just check the value to see if the value beings with the string 'anonymous'. You can write more complex versions that take any number of arguments. (See the doc for an example.)
So once I have this validation method, I can apply it to my name rule:
2 required: true,
3 minlength: 2,
4 noanon: true
5},
So now my name field must be entered, must have at least two characters, and must pass my custom rule. You can see an example of this here: http://www.coldfusionjedi.com/demos/jqueryvalidation/test31.html
Ok, so now I've actually written a bit of code, but frankly, for what I've got now the code is minimal.
Alright, so far we've looked at 2 options to the core validate constructor - rules and messages. Obviously there is quite a bit more. You can peruse the list here, but I'll wrap up with one more example. I mentioned yesterday that I tend to prefer my errors on top of the form. I will typically put these in a nice bulleted list. The plugin makes this rather simple. I can supply options for a container to use for the errors, a place to store each error, as well as HTML to use to wrap the errors. Consider this example:
2
3errorContainer: "#errorbox",
4errorLabelContainer: "#errorbox ul",
5wrapper: "li",
6... more code here ...
I then added this style to my page:
2#errorbox {
3 background-color: yellow;
4 display: none;
5}
6</style>
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:
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.


The Form Validation stuff should be very useful in the future. Thanks Ray.
Error Screen: http://i42.tinypic.com/foptea.jpg
rules: {
name: "required",
email: {
required: true,
email: true,
}, //this comma is throwing an exception
comment: "required"
},
http://ejohn.org/blog/server-side-javascript-with-...
rules: {
name: "required",
email: {
required: true,
email: true, //this comma is throwing an exception
},
comment: "required"
},
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
http://www.accessify.com/tools-and-wizards/develop...
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"
});
http://www.mail-archive.com/jquery-en@googlegroups...
From the creator himself.
$.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.
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
"name.moon": {
required: true,
minlength: 2
}
Thanks, Ray
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
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
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
Make sense?
So, I will have to play with this
errorPlacement: function(error, element) {
}
Thanks for the help
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!!!!!
foo,
moo,
to
foo
,moo
If you look at my later blog entries in this series, I believe I switched to this format.
Thanks for any help.
I didn't found the solution for this with checkboxes.
Thanks.
I would check this out:
http://jquery.bassistance.de/validate/demo/
He has a demo just for checkboxes and selects.
Thanks and great tutorial by the way.
john
('/^[a-z0-9\.\-_]+$/')
Any idea how to write that w/ JQuery Validator?
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!!!
<!--- user registration page --->
rules:
{ email:{remote:{url:"emailCheck.cfm",type:"post"}}
}
<!--- emailCheck.cfm --->
<cfset getPageContext().getOut().clearBuffer() />
<cfsetting enablecfoutputonly="true">
<cfsilent>
<cfset o_main = createObject("component","cfcs.main")>
</cfsilent>
<cfoutput>#trim(o_main.checkEmail(email=form.email))#</cfoutput>
<!--- main.cfc --->
<cffunction name="checkEmail" access="remote" returnType="boolean">
<cfargument name="email" type="string" required="true">
<cfset var qCheckEmail = "">
<cfquery name="qCheckEmail" datasource="#application.datasource#">
select record_id
from users
where email = '#arguments.email#'
</cfquery>
<cfreturn not qCheckEmail.recordcount>
</cffunction>
So, if the email is not in use already, we'll get a boolean yes returned.
However, there is a bunch of whitespace above the YES as I view it in firebug, which I can't get rid of and it's wrecking my nice boolean.
As you can see, I've used various techniques such as <cfsilent> and clearbuffer, but there still whitespace. How do I get rid of it or somehow dig the boolean out of the whitespace so the callback sees only a "yes", not "whitespace-yes"? Hope I'm making sense.
May i know how i can show the custom error message for each field form in a specific area?
eg
First name [ textbox ]
<span id ="firstname"></span>
When the First Name is not enter, the custom error message will showed in <span id ="FirstName"> ?
Another question is, How i can used this jquery validation with the submit form with button type = [button] instead of type = [submit]?
http://jquery.bassistance.de/validate/demo/multipa...
Thank for your update and link, very appreciate it.
But It seem little bit difference compare with the once i looking for.
Actually im looking something like :
Jquery script (with Javascript? possible?)
If First name not entered
If Error, Set custom error message :" Please enter your first name"
-- Showed in <span id ="FirstName">
Elese
Set message :" First name Entered"
-- Showed in <span id ="FirstName">
If dateis entered
-- Calling Custom Jscript to do more checking
If Error, Set custom error message :" Please enter valid date"
-- Showed in <span id ="FirstName">
Elese
Set message :" Date entered"
-- Showed in <span id ="FirstName">
-- HTML Code --
First name [ textbox ] <br><br>
<span id ="firstname"></span>
Date [ textbox ] <br><br>
<span id ="date"></span>
<input type="button" value="submit">
1) When the First Name is not enter, the custom error message will showed in <span id ="FirstName">
Most of the sample i found in internet din't have such sample.
Of course, the message showed in span will vary depend of the Validation result.
2) Another question is, How i can used this jquery validation with the submit form with button type = [button] instead of type = [submit]?
Im only can found those sample used button Type = [submit] but not Type = [button].
Any idea?
2) It's been a while - but if I remember, you can run the validation programmatically. You would just use jQuery to bind to the click event of your button.
I think i did figure out how to showed the custom message now, by using below script :
errorPlacement: function(error, element) {
jsSetIDName = $('#' + element.attr("name") + '_msg').fadeIn();
error.appendTo(jsSetIDName);
}
where by the attr("name") is your span ID : ID attribute.
But i still unable to figure out how to used button to control the validation process eg : Click [Update] or [Convert] etc..
I may used hidden variable , eg FinalAction = [?]to control this when sent the form for processing..
I have several question here :
1) how we can fadeIn and FadeOut the validation text? I only can figure out when click the Submit button, but not when user edit the form field.
2) Adding Custom Jscript , eg DateCompare (FromDate, Todate) and then return the result? I will try using the "addMethod" to plug in my current jscript..
To your second one - yeah - give it a shot. That's all I can offer. :)
[Add Comment] [Subscribe to Comments]