Validating Dropdowns

May 11, 2009 at 7:26 PM

What is the suggested way of applying validation to a dropdown?  

I want to make the field required, so I added the [Required] attribute (from DataAnnotations), and also added the ValidationMessage for the field.  I'm also using MVCContrib FluentHTML, so my <select> renders with 

<option value="0" selected="selected">Select</option>

so the default value is zero, which satisfies the required attribute.  Instead I went with [Range] and put a validation of > 0, which works, but I still get some interesting behavior.  The client validation will fire successfully making my dropdown red in appearance, but it still allows the form to submit which causes the server side validation to fire (which works fine).  

How can I get the client side validation to work the same way it does with textboxes?

Thanks for any help!

May 11, 2009 at 8:53 PM

I've got a resolution to the second half of my question.  I was using an incorrect version of jQuery.

Still would like to know how to apply the [Required] attribute to a dropdown though.


May 12, 2009 at 6:49 AM

Can you set the default value to an empty string? i.e.:

<option value="" selected="selected">Select</option>

Does that work with [Required]?

Jun 3, 2009 at 8:15 PM

Can anyone please explain how to get client-side validation for a dropdown to work like textboxes?

Steve, What version of jQuery did you change to to get this working? I have tried v1.2.6 and v1.3.2 with no change in behavior.

What I am experiencing is client-side validation for the dropdown but only onblur, unlike the the textboxes which validate on keyup.

This is my markup...

<select id="CategoryId" name="CategoryId">
   <option value="">[ Select Category ]</option>
   <option value="3">Category1</option>
   <option value="7">Category2</option>
   <option value="2">Category3</option>
   <option value="1">Category4</option>
Thanks for any help!!