An Introduction to jQuery and Form Validation (2)

This post is more than 2 years old.

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:

<input id="cname" name="name" size="25" class="required" minlength="2" />

To mark a field as requiring a valid URL, you would do:

<input id="curl" name="url" size="25" class="required url" />

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.

<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>

Now here is an exact copy that specifies the rules in JavaScript instead:

<html>

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

rules: {
	name: "required",
	email: {
		required: true,
		email: true,
	},
	comment: "required"
}

});

}); </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" /> </p> <p> <label for="cemail">E-Mail</label> <em></em><input id="cemail" name="email" size="25" /> </p> <p> <label for="ccomment">Your comment</label> <em>*</em><textarea id="ccomment" name="comment" cols="22" ></textarea> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form>

</body> </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:

<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" /> </p> <p> <label for="ccomment">Your comment</label> <em>*</em><textarea id="ccomment" name="comment" cols="22" ></textarea> </p> <p> <label for="csub">Subscribe to newsletter?</label> <input type="checkbox" id="csub" name="csub" /> </p>

<p> <label for="cemail">E-Mail</label> <input id="cemail" name="email" size="25" /> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </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.

rules: { name: "required", email: { required: "#csub:checked", email: true, }, comment: "required" }

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:

messages: { comment: "This is a comment form. Why in the heck would you leave the comment blank?", email: { required: "Dude, you want the newsletter, but you didn't enter an email address?", email: "Email addresses are of the form user@host. Not yourRstupid." }, name: { required: "Stand up for your comments or go home.", minlength: jQuery.format("You need to use at least {0} characters for your name.") } }

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:

$(document).ready(function(){ $("#commentForm").validate({

rules: {
	name: {
		required: true,
		minlength: 2
	},
	email: {
		required: "#csub:checked",
		email: true,
	},
	comment: "required"
},
messages: {
	comment: "This is a comment form. Why in the heck would you leave the comment blank?",
	email: {
		required: "Dude, you want the newsletter, but you didn't enter an email address?",
		email: "Email addresses are of the form user@host. Not yourRstupid."
	},
	name: {
		required: "Stand up for your comments or go home.",
		minlength: jQuery.format("You need to use at least {0} characters for your name.")
	}
}

});

});

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:

$.validator.addMethod("noanon", function(value) { return value.toLowerCase().indexOf("anonymous") != 0; }, '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:

name: { required: true, minlength: 2, noanon: true },

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:

$("#commentForm").validate({

errorContainer: "#errorbox", errorLabelContainer: "#errorbox ul", wrapper: "li", ... more code here ...

I then added this style to my page:

<style> #errorbox { background-color: yellow; display: none; } </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:

<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.

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 Kumar posted on 2/10/2009 at 11:33 PM

Examples look good on FF, don't work on IE. But yes, I have been quite impressed with jQuery too, mainly working with jqGrid till now though (much faster than cfgrid).

The Form Validation stuff should be very useful in the future. Thanks Ray.

Comment 2 by Raymond Camden posted on 2/10/2009 at 11:34 PM

What fails in IE? What version of IE?

Comment 3 by Kumar posted on 2/10/2009 at 11:38 PM

IE7, the last example, just submits the form for me (all fields left blank).

Error Screen: http://i42.tinypic.com/fopt...

Comment 4 by Gabe posted on 2/10/2009 at 11:38 PM

Both of these have been really insightful. Wish I could have found something like this a little over a year ago when I was struggling with jQuery form validation. Of course, it's always important to remind clients that javascript form validation is still no substitute for verifying and cleaning data submitted to a form. But, the jQuery form validation plugin is a vast improvement over what CF is doing in CFFORM. The level of control over returned error messages and combination validations (requiring field validation based on input in other fields) makes it valuable tool in any developers box of tricks.

Comment 5 by Gabe posted on 2/10/2009 at 11:41 PM

In your rules area, there is an error in IE7.

rules: {
name: "required",
email: {
required: true,
email: true,
}, //this comma is throwing an exception
comment: "required"
},

Comment 6 by Jim Priest posted on 2/10/2009 at 11:47 PM

I really need to find some time to play with Jaxer - server side JS. Then you could validate on both ends using the same code...

http://ejohn.org/blog/serve...

Comment 7 by Gabe posted on 2/10/2009 at 11:47 PM

Sorry, wrong line, it's the trailing comma here:

rules: {
name: "required",
email: {
required: true,
email: true, //this comma is throwing an exception
},
comment: "required"
},

Comment 8 by Dan G. Switzer, II posted on 2/11/2009 at 12:01 AM

IE does not like Objects that have a trailing comma with null data after it (which is what Gabe was pointing out.)

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 by Michael Brennan-White posted on 2/11/2009 at 1:35 AM

I just found a pretty cool page which will help the Javascript dyslexic like me when creating jQuery functions. It is a wizard based jQuery function builder

http://www.accessify.com/to...

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

Thanks for the IE info there. I'll try Dan's format for my next demo.

Comment 11 by Scott Stroz posted on 2/11/2009 at 4:05 AM

jQuery is like the CF of JavaScript libraries. It can do a whole lot of shit with very little code.

Comment 12 by Garrett Johnson posted on 2/11/2009 at 4:11 AM

This is a great plug-in, we use it at worshipplanning.com for our sign up form. (http://worshipplanning.com/...

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 by brian posted on 2/11/2009 at 5:15 AM

I tried class="required minlength:2" for a select but it's not quite right. What's the format for selects?

Comment 14 by Raymond Camden posted on 2/11/2009 at 6:55 AM

Not that it helps, but 'minlength' would refer to the length of a text value, not the number of selected items. Let me try to dig a bit on that.

Comment 15 by Raymond Camden posted on 2/11/2009 at 6:57 AM

Here ya go:

http://www.mail-archive.com...

From the creator himself.

Comment 16 by Jörn Zaefferer posted on 2/12/2009 at 3:44 AM

Another note from the author: You can make your custom methods much more robust by adding a call to this.optional:

$.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/Plug...">minlength</a> works with inputs of type text, checkboxes and selects.

Comment 17 by Raymond Camden posted on 2/12/2009 at 3:54 AM

Thanks for the tip, Jorn.

Comment 18 by brian posted on 2/12/2009 at 4:01 AM

thanks Jörn, that works great

Comment 19 by Byron Raines posted on 2/21/2009 at 11:10 PM

Ray,

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 by Raymond Camden posted on 2/22/2009 at 2:36 AM

Wrap the name in quotes:

"name.moon": {
required: true,
minlength: 2
}

Comment 21 by Byron Raines posted on 2/22/2009 at 2:55 AM

Sweet. Works like a charm.

Thanks, Ray

Comment 22 by cucumucz posted on 2/23/2009 at 1:34 PM

Well elaborated !

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 by Raymond Camden posted on 2/23/2009 at 6:58 PM

You don't see how to define customized messages in the code above?

Comment 24 by Mark S posted on 2/28/2009 at 5:26 AM

Hi, I am a bit late to the party but have a question:

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 by Raymond Camden posted on 2/28/2009 at 5:38 AM

Just use the messages block as described above. If you want to use another sentence along with what jquery uses by default, you would just specify both in the messages block.

Comment 26 by Mark S posted on 2/28/2009 at 5:42 AM

Thanks Ray,

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 by Raymond Camden posted on 2/28/2009 at 5:44 AM

Hmmm. Then you may need to tie into the events that Validation supports. Notice the error event, and handle doing the 'special' message.

Make sense?

Comment 28 by Mark S posted on 2/28/2009 at 7:18 AM

I think so.

So, I will have to play with this

errorPlacement: function(error, element) {

}

Thanks for the help

Comment 29 by mahendra posted on 3/20/2009 at 4:21 PM

hi
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 by Raymond Camden posted on 3/21/2009 at 2:21 AM

@mahendra: Someone, I forget who, told me that use of commas in the JS code can break IE. They said to switch from:

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 by John posted on 4/2/2009 at 2:04 PM

Hi, perhaps somebody can help me, I try to validate on several checkboxes in fieldsets. For example, I have 4 checkboxes and I want to require at least 2 of them. And I simple try to view the error message under the 4 checkboxes.

Thanks for any help.

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

John, please check the docs for the validation plugin. Your scenario is exactly something they support.

Comment 33 by John posted on 4/2/2009 at 3:37 PM

You're right, I got a working example form the demos of the plugin, but only with the metadata plugin. I try to find a solution like in example: test30.html

I didn't found the solution for this with checkboxes.
Thanks.

Comment 34 by Raymond Camden posted on 4/2/2009 at 4:57 PM

The metadata rules work just as easy, if not easier, in pure JS, which is covered in my series. I don't mean to keep pushing you to the docs, but, this _is_ covered there. Or you are at least given the _rules_ you can do.

I would check this out:

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

He has a demo just for checkboxes and selects.

Comment 35 by John posted on 4/2/2009 at 6:35 PM

Thanks for the advice, I did look at the example, but my problem were just the '[]' brackets for the name tag of my checkboxes and even the necessary label for the error message. It now works.

Thanks and great tutorial by the way.

john

Comment 36 by Joe Devon posted on 5/14/2009 at 5:49 AM

Thanks for a great tutorial! I'm a javascript newbie though, so I need help on a custom validator. I'm trying to use this REGEX:
('/^[a-z0-9\.\-_]+$/')
Any idea how to write that w/ JQuery Validator?

Comment 37 by Raymond Camden posted on 5/14/2009 at 3:36 PM
Comment 38 by José Luis posted on 5/15/2009 at 12:31 AM

Hello everybody!!

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 by Raymond Camden posted on 5/15/2009 at 12:42 AM

Well, it looks like you didn't do any validation. Your code just always hides the button. Period. You would want to hide it on _successful_ validation.

Comment 40 by José Luis posted on 5/15/2009 at 12:51 AM

sorry and how can I do that whi jquery-validate or jquery or javascript??.... If have any reference.... thanks

Comment 41 by Raymond Camden posted on 5/15/2009 at 4:47 AM

This page itself, and the related links in the article, discuss form validation and jQuery. Please read the links, and the jQuery documentation.

Comment 42 by Joe Hansen posted on 12/31/2009 at 11:31 PM

Awesome Tutorial. Learnt JQuery Validation within minutes! Thank you very much Raymond! No wonder "Everybody loves Raymond!" :)

Comment 43 by pbaylis posted on 10/7/2010 at 11:25 AM

I've been a-fiddlin' with the email rule to check if email has already been used by a subscriber. But, I'm running into an issue. I'm sure what I've got can be done better.

<!--- 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.

Comment 44 by Raymond Camden posted on 10/7/2010 at 3:56 PM

Try adding output="false" to your CFC method. Worse comes to worse, in jQuery you can $.trim(x) where X is the response.

Comment 45 by keong posted on 4/28/2011 at 11:05 AM

Hi,
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]?

Comment 46 by Raymond Camden posted on 4/28/2011 at 3:05 PM

This demo shows an example of that.

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

Comment 47 by keong posted on 4/29/2011 at 9:25 AM

Hi Raymond
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?

Comment 48 by Raymond Camden posted on 4/29/2011 at 3:23 PM

Maybe i'm not just reading you right. The core thing in your #1 to me is - show the error in a div the field. The plugin supports that and the demo I showed demonstrates that. Does it not?

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.

Comment 49 by keong posted on 5/11/2011 at 2:28 PM

Hi Raymond

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..

Comment 50 by Raymond Camden posted on 5/12/2011 at 4:33 PM

No idea about your first question. You may want to contact the plugin author?

To your second one - yeah - give it a shot. That's all I can offer. :)

Comment 51 by Helen Neely posted on 8/30/2011 at 2:23 AM

Thanks for this post. I just started working with jQuery and needed a way to override the default error messages on the form. Your examples here have helped. I don't have to rll my own Javascript to validate forms anymore :)

Comment 52 by Andrea posted on 5/22/2012 at 3:07 AM

Thanks for your article. I need your help to solve my problem. I want to validate a checkbox by his ID inside rules, but I don't know how.
<input type="checkbox" name="language" id="french">
<input type="checkbox" name="language" id="english">
<input type="checkbox" name="language" id="italian">

$("#settete").validate(
{
rules:{
'language[2]':{
required: true
}
},
messages:{
....}
How to select checkbox with ID="Italian"? Thanks in advance

Comment 53 by Raymond Camden posted on 5/22/2012 at 10:37 PM

Check out the responses here: http://stackoverflow.com/qu...

Comment 54 by Greg posted on 10/16/2012 at 2:29 AM

Hello,
I have 3 input text fields in my form. I want the user to fill à least one these 3 fieds. Is it possible to have this rule with the plug-in ?
Tnacks a lot !

Comment 55 by Raymond Camden posted on 10/16/2012 at 9:33 AM

Yep - check all the entries in this series - I'm pretty sure I discussed custom rules some place. If not though, yes, you can have any custom logic you wish.

Comment 56 by Greg posted on 10/17/2012 at 8:16 PM

Hi,
I didn't found a similar example in the previous posts. I saw how to do with checkboxes (at least 2 checked) but not with text fields... I have inderstood how the plug in works for basic controls but i'm limited for these kind of specifical cases.
Can somebody help me ?

Comment 57 by Raymond Camden posted on 10/18/2012 at 10:16 AM

Well the rule for "at least two checkboxes" demonstrates how to do custom rules, right? You would just need to change the logic to get the values of your text fields and ensure at least 2 have values.

Comment 58 by Greg posted on 10/19/2012 at 1:50 AM

Hi !

My problem is that every checkbox field has the same name, whereas my 3 text fields don't have.
For checkboxes the code is :

topic: {
required: true,
minlength: 2
},

for

<input type="checkbox" value="Topic1" name="topic" /> Topic 1
<input type="checkbox" value="Topic2" name="topic" /> Topic 2
<input type="checkbox" value="Topic3" name="topic" /> Topic 3

But for text fields, "minlength" "makes the element require a given minimum length" (from the documentation) so how to apply the rule to 3 fields with different name. Here are my 3 fields I want the user to fill in at least one :

<input type="text" name="telephone">
<input type="text" name="mobile">
<input type="text" name="mail">

Maybe I don't see something obvious... Coding is not my full time job ! :-) et sorry for my English.

Thanks !

Comment 59 by Raymond Camden posted on 10/19/2012 at 9:39 PM

You want to look at the example in this post, the noanon rule. That shows you how to do custom validation. You would modify the code inside the method to check those text fields. Does that make sense?

Comment 60 by Greg posted on 10/21/2012 at 3:17 AM

Ok I understand. Unfortunately i'm not good enough in javascript to write a custom rule... I'm gonna use PHP... not user friendly but that's all i can do ! Thanks.

Comment 61 by Raymond Camden posted on 10/21/2012 at 5:43 AM

You could also use this as an opportunity to *learn* JavaScript. It will compliment your PHP knowledge.

Comment 62 by Greg posted on 10/21/2012 at 1:17 PM

You're completely right. I don't have time right now and i have to advance on this project. But I will come back on it !

Comment 63 by Jai posted on 2/19/2013 at 7:03 PM

Thanks for displaying error in different ways and styles. I like most the last one which is used by team for joomla custom project.

Comment 64 by Jai posted on 2/19/2013 at 9:07 PM

Hi Ray,
I have 5 fields and want to display only 1 message 'Please fill all fields' if user left any of field blank. Any help would really be great. One input box is SELECT and rest are just text boxes. Please help

Comment 65 by Raymond Camden posted on 2/19/2013 at 9:13 PM

The plugin supports that, but I can't remember the syntax off the top of my head. Please read their documentation for details.

Comment 66 by Jai posted on 2/19/2013 at 9:17 PM

OK. Thanks for quick reply :)

Comment 67 by Pat posted on 7/22/2014 at 5:03 PM

Hello i've problems to get the validation right with a select box.(aantalpers)
An input field works fine! (name).

*Here my code!*

_*HTML*_
<div data-role="content">
<form action="retour.php" method="post" id="formretour" name="formretour">

<div data-role="fieldcontain">
<label for="name" class="name"><h3>Your Name:</h3></label>
<input type="text" name="name" id="name"class="required">
<span id="forgetname"class="forgetfilltext"> </span>
</div>

<div data-role="fieldcontain">
<h4>How many persons:</h4></br>
<label for="aantalpers" class="select"></label>
<select name="aantalpers" id="aantalpers"class="required number" min="1" max="100">
<option value="0"disabled="disabled"selected="selected">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
</select>
<span id="forgetpersons"class="forgetfilltext"> </span>
</div>

_*JQuery*_

<script><!-- deze werkt!!! voor een textveld-->
$(document).ready(function() {
$("#formretour").submit(function() {
if ($("#name").val() == "") {
$("#forgetname").html("Don't forget to fill in your name!").show();
return false;}
else{ return true;
}
});
});
</script>

-------------------------

Anybody knows how to code the select box validation?