jQuery Form Validation with Selects

This post is more than 2 years old.

A reader on my first post on jQuery Form Validation asked an interesting question - how do you validate select form fields? Specifically, given that a drop down may have a 'Other' option, how do mark a text field required if the drop down is set to Other?

Before I answer that, let me first point out a simpler example. Given a drop down where the first option is 'Pick one of the below', how do you require a user to select one of the other items? Easy! Just make the first option have a blank value. Consider:

<select id="cjob" name="job"> <option value="">Select a Job</option> <option value="1">Jedi</option> <option value="2">Annoying Droid</option> <option value="3">Bad Guy</option> </select>

Notice how all the options, except the first, have a value? By just setting this drop down to required in our rules block, jQuery will handle ensuring that the user doesn't leave the drop down on the first option. To be honest, even with all the respect I've gained for jQuery, I didn't think it would be that easy. You can even specify that the user select a certain number of options (for multi-select drop downs) or that they must select a certain number but no more than some max. The plugin author has a nice demo page with examples of that. What I didn't see, though, was an example that matched what the reader wanted. If the drop down is on 'other', make some other field required. Here is how I solved it.

First, our 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="cjob">Job</label> <em>*</em><select id="cjob" name="job"> <option value="">Select a Job</option> <option value="1">Jedi</option> <option value="2">Annoying Droid</option> <option value="3">Bad Guy</option> <option value="other">Other (Enter Below)</option> </select> </p> <p> <label for="cother">Other Job:</label> <input id="cother" name="otherjob" size="25" /> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form>

The form has 3 main fields: Name, Job, and Other Job. I want name to be required. I want job to be required. If you select Other for a job, I then want Other Job to be required as well. Here is the rules block I used:

rules: { name: { required: true, minlength: 2 } ,job: { required: true } ,otherjob: { required: function(element) { return $("#cjob").val() == 'other' } } }

Let's skip the first rule since it isn't anything new. The second rule applies just to the drop down. The use of required here will ensure that an option with some value has been picked. If I leave it on the first option there will be no value and the rule will fail. The third rule is where things get interesting. I essentially provide an inline function that returns true or false. The field will be required if and only if the value of cjob (my drop down) is set to other.

Next, I ensured my messages made all of the above clear:

messages: { name: { required: "Stand up for your comments or go home.", minlength: jQuery.format("You need to use at least {0} characters for your name.") } ,job: "You must select a job." ,otherjob: "If you select 'other' for a job, you must enter it." }

Pretty simple, right? Can anyone recommend an alternate way of solving this? You can find a demo of this code here:

http://www.coldfusionjedi.com/demos/jqueryvalidation/test4.html

p.s. I think I may forgo Star Wars for my next tattoo and just do 'jQuery FTW'. Or is that too fan boy?

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 Sebastiaan posted on 2/16/2009 at 7:50 PM

I've been using Prototype for a while now, but seeing all the excellent examples you've come up with recently, I think I'll make the switch to jQuery when I rework n number of forms for a client during the next couple of weeks. This is really deadsimple (I say before having ventured into my task!) ;-)

Comment 2 by salvatore fusto posted on 2/16/2009 at 8:14 PM

Hi Ray,
may be i've not understood requirements; if you set the job select as required, form is validated only if you select a job: your test4.html works this way.
but i think that your reader wants that jobs select in not a required field, but he wants that, if no job is selected, other job field became required: to do so you have not to validate job field, and validate other job field as you have done.
do you agree?
regards
salvatore

Comment 3 by Raymond Camden posted on 2/16/2009 at 8:15 PM

Um, I'm having a real hard time parsing your English. If you mean, "he wanted the other field required if you selected other, but no other validation", then just remove required from job. That's it.

Comment 4 by salvatore fusto posted on 2/16/2009 at 8:30 PM

Hey Ray,
first of all, excuse my poor English.
What i mean is:
1)The "Name" field is rquired;
2)The "Other job" field is required if, and only if, user does not select any job from this select
so the rules are:
rules: {
name: {
required: true,
minlength: 2
}

,otherjob: {
required: function(element) {
return $("#cjob").val() == 'other'
}
}
}
are these the required rules ?
regards
salvatore

Comment 5 by Raymond Camden posted on 2/16/2009 at 8:33 PM

Right. My example goes a bit too far probably. :)

Comment 6 by Jörn Zaefferer posted on 2/16/2009 at 9:26 PM

Your implementation is pretty much the way to go. You could probably replace the callback with a selector: required: "#cjob[value=other]".

Comment 7 by Raymond Camden posted on 2/16/2009 at 9:29 PM

Wow, didn't know that style of selector worked. Nice!

Comment 8 by Chris posted on 2/18/2009 at 2:43 AM

Thanks Ray! Worked like a charm!

Comment 9 by Patrick Flynn posted on 2/26/2009 at 11:50 PM

What if you want to set a default message for all required fields, would you have to specify the message for each individual field or is there a way to change the overall message for a required field? Essentially I prefer having a an asterisk show up upon validation rather than the message.

Comment 10 by Raymond Camden posted on 2/27/2009 at 1:53 AM

Not sure if this is documented/supported/whatever, but you can manually set it at the plugin level:

jQuery.validator.messages.required = "*";

That would set the message for required. You would need to repeat it for email, url, etc.

Comment 11 by Byron Raines posted on 3/4/2009 at 9:04 AM

Ray,

Enjoying these write-ups. I've have the select validation working from your example. If the "other" field is left blank as per the validation rules, it shows my error message, however the select box reverts back to (in my case) "Choose One". So I have to reselect "Other". Is this the correct behavior. I can't seem to find anything about this in the docs.

Thanks

byron

Comment 12 by Raymond Camden posted on 3/4/2009 at 9:08 AM

What browser? I'm not seeing that in OSX FF.

Comment 13 by Byron Raines posted on 3/4/2009 at 10:13 AM

OK. I just checked again and things are behaving properly. Maybe I've been just staring at the screen to long or might have been refreshing the screen or something.

Anywho, thanks for getting back to me, and again for all your write-ups. They are informative and helpful.

jQuery is very cool.

Comment 14 by Byron Raines posted on 3/4/2009 at 10:24 AM

Oh, by the way. I have a situation where I have a list of yes/no questions. If they answer 'yes' to a question, they must answer another question for the field. Like:

var1: yes/no var1comment: text
var2: yes/no var2comment: text

on so

I know how to enable and validate the comment box. Do I have to have a separate $('var1'), $('var2') for each one (I have many), or is there someway to consolidate that. I was think there maybe someway using a "for each" type method, but not sure it works that way.

I guess a could do it with "regular" javascript functions with onClick on the <input>, but would like to try it with jQuery.

Maybe a write up if it can be done??

Thanks again

Byron

Comment 15 by Raymond Camden posted on 3/4/2009 at 8:16 PM

I believe - stress believe - that the the rules portion must point to precise field sets, so you couldn't match _any_ yes/no block. I believe you would need to do this then with one of the events the plugin requires. I haven't dug into this yet, but I know you can do really customized stuff on submit. This is a great example. My time is a bit short this week, but I'll try to work up a demo.

Comment 16 by Byron Raines posted on 3/5/2009 at 1:22 AM

Thanks, Ray. Will look forward to it. I'll keep poking around to see what I can figure out.

Byron

Comment 17 by Mark posted on 4/15/2009 at 4:28 PM

Hi Ray,
Thanks for the tutorial, its helped me a lot! I just want to know how to remove on submit validation. i just need on blur and key up.
Thanks in advance

Comment 18 by Mark posted on 4/15/2009 at 4:39 PM

Sorry I never looked around properly first
onsubmit:false does the trick

Comment 19 by vandy posted on 6/8/2009 at 9:33 PM

Hi,

I have a user control on a page. In user control some fields have validation. I did the validations by using class properties, but I want to call some method on onsubmit of form. Since the validation occurs on onsubmit event of form, I am scared that the method I want to call may not be called. I can use submit behavior at the form level but I dont know what to do at the control level, I mean how to add methods to form's submit event from a control if we are using for validation of jquery.

Comment 20 by Gustavo posted on 8/11/2009 at 9:17 AM

Thanks Raymond, simple solution for forcing one selection.. by Jquery, minlength: 1 is enought-

Comment 21 by Kevin posted on 9/22/2009 at 11:59 PM

Great code! I used your example and modified it to use checkboxes instead. Im new to jQuery dev, it took me forever to get it to work! Im sure it can be done simpler.

http://psylicyde.com/misc/j...

Comment 22 by Aloel posted on 11/17/2009 at 10:34 PM

Is there a different format for validation of radio buttons? I think Kevin's example showed that checkboxes validate the same as text inputs. Am I correct?

Comment 23 by Raymond Camden posted on 11/17/2009 at 11:50 PM

As far as I know, it should be the same.

Comment 24 by Aloel posted on 11/18/2009 at 6:56 PM

Thanks! I finally got 8 forms all validated and working as expected!

Comment 25 by Jeff Self posted on 9/16/2010 at 8:21 PM

Wow! This is exactly what I was looking for. Great job posting this, Ray!

Comment 26 by P. posted on 10/27/2010 at 12:19 PM

For radio buttons, I used this:

,otherjob: {
required: function(element) {
return ($("input[name='job']:checked").val()) == 'other';
}
}

Comment 27 by Jeff posted on 11/19/2012 at 2:04 PM

Hi Raymond,

Im using the latest jquery 1.8, im trying to validate my select using your example, I couldnt get it to work. is it compatible with jquery mobile?

Comment 28 by Raymond Camden posted on 11/19/2012 at 7:53 PM

jQuery Mobile updates the DOM quite a bit, so while you _can_ do validation with JQM (I've got another blog post on it - http://www.raymondcamden.co... you would need to modify the code you see here.

Comment 29 by mj posted on 1/22/2014 at 8:02 PM

hi raymond, i'm doing a form validation, pretty much alike yours. Difference is that I put an ok green icon when option is selected. Suppose I choose an option from the drop down menu. Because it is a required field an ok green icon appears. Then I change it to the default option (like "select an option") but the ok green icon is still there when it should be in red saying "please select an option". What am I missing? Thanks!!

Comment 30 by Raymond Camden posted on 1/22/2014 at 10:04 PM

I honestly don't remember how the plugin handles selects, but it should be possible to tell it the first option is not valid.

Comment 31 by Raymond Camden posted on 1/22/2014 at 10:05 PM

mj: I went to the demo page I linked to (the plugin demo, not mine) and his select does exactly that. If you select the first (empty) option it considers it an error. Please see his demo.

Comment 32 by mj posted on 1/24/2014 at 7:46 PM

@RaymondCamden thank you Raymond, I could make it work, I was just missing this part of the code:

$('.chosen, .chosen-with-diselect', form2).change(function () {
form2.validate().element($(this));
});
}

Comment 33 by Zad Imam posted on 4/17/2014 at 7:36 PM

Ray, I know this post is a bit outdated, but somewhere along the line your jquery library files got lost and your demos no longer work :-(.

Comment 34 by Raymond Camden posted on 4/17/2014 at 7:38 PM

Yeah - I ran into this with another post a bit ago. Hopefully folks will just download. :)