I have a contact form. It asks for your name and then it asks you whether you'd like to be contacted via telephone or email. The telephone and email fields are hidden unless the user selects a radio button for telephone or email. Once you click on either telephone or email I validate whether they input a correct telephone or email address.
My question is how to check with JQuery Validation and print out an error message if the user hasn't clicked on either radio button?
Update (2012-01-20 19:38): I think I understood what you were looking for and noticed that you wanted to use jQuery's Validation plugin.
Here is a working Demo on JSFiddle (Note: I forked from Sparky's fiddle)
By default, only the rule regarding the radio buttons is set. All the messages are set in advance, and the specific fields of the form are hidden. Now whenever a radio button is clicked, I hide the useless field, remove the corresponding rule. I also show the right field and add the corresponding rule.
The specific piece of code you were looking for must be something like:
First answer: You say that when the user select one of the two radios (email or telephone), you display one or the other corresponding field. Therefore, I assume that you already have some jQuery code which runs every time the user clicks on one radio button.
This code could add a class or a hidden field or whatever you prefer (or whatever is the best common practice for this case, I am unfortunately not experienced enough to know that...) which let you know later that the user did select an option.
If you can show more of the code (a jsFiddle for instance) I could give you a more specific answer. Still, here is what I would do:
The test is always the same:
Let me know how that helps.
Are you simply asking how to validate a set of radio buttons? Since you've shown no code, all I can show you is how you would validate a set of
radio
input
's with the plugin.Then you would dynamically add/remove rules from the corresponding inputs using the built-in
rules
method. Again, I'd need to see your code before customizing a solution.Working Demo: http://jsfiddle.net/PbHwX/
jQuery:
HTML:
Documentation: http://docs.jquery.com/Plugins/Validation
you can use jquery unobtrusive if you are many form and use ASP.NET MVC etc.. or you can do something like this :
Demo