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?
Archived Comments
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!) ;-)
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
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.
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
Right. My example goes a bit too far probably. :)
Your implementation is pretty much the way to go. You could probably replace the callback with a selector: required: "#cjob[value=other]".
Wow, didn't know that style of selector worked. Nice!
Thanks Ray! Worked like a charm!
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.
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.
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
What browser? I'm not seeing that in OSX FF.
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.
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
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.
Thanks, Ray. Will look forward to it. I'll keep poking around to see what I can figure out.
Byron
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
Sorry I never looked around properly first
onsubmit:false does the trick
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.
Thanks Raymond, simple solution for forcing one selection.. by Jquery, minlength: 1 is enought-
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...
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?
As far as I know, it should be the same.
Thanks! I finally got 8 forms all validated and working as expected!
Wow! This is exactly what I was looking for. Great job posting this, Ray!
For radio buttons, I used this:
,otherjob: {
required: function(element) {
return ($("input[name='job']:checked").val()) == 'other';
}
}
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?
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.
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!!
I honestly don't remember how the plugin handles selects, but it should be possible to tell it the first option is not valid.
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.
@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));
});
}
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 :-(.
Yeah - I ran into this with another post a bit ago. Hopefully folks will just download. :)