How to display an unobtrusive jQuery validation message for a dropdown when changing a selection?

Setup:

  • ASP.NET MVC 4 with client-side validation (+ unobtrusive javascript).
  • jquery 1.8.2
  • jquery.validate 1.10.0
  • jquery.validate.unobtrusive

html:

<form action="/" method="post"> <select data-val="true" data-val-required="DropDown is required." id="DropDown" name="DropDown"> <option value="">Select a letter</option> <option>A</option> <option>B</option> <option>C</option> </select> <span data-valmsg-for="DropDown" data-valmsg-replace="true"></span> <br/> <button type="submit">Submit</button> </form>​ 

You can see it in action here .

The server-side code for the drop-down list is pretty uninteresting:

 // View Model public class ViewModel { [Required] public string DropDown { get; set; } } // View @Html.DropDownListFor(m => m.DropDown, new SelectList(new[] { "A", "B", "C" }), "Select a letter") 

And here are the steps to see the problem:

  • Use the mouse to select one of the values ​​(A, B, C).
  • Use the mouse to select the default, empty, value (select a letter). The desired message is not displayed.
  • Use the arrow keys to select one of the values ​​(A, B, C).
  • Use the arrow keys to select the default value, empty, value (select a letter). This time the desired message is displayed.
  • Use the mouse to select one of the values ​​(A, B, C). The required message disappears.
  • Use the mouse to select the default, empty, value (select a letter). A mandatory message will appear.

Events don't seem to trigger mouse events until the first time a check is activated (either by changing the values ​​from the keyboard or by pressing the submit button). Any explanations as to why this is happening (am I doing something wrong?) Or workarounds would be greatly appreciated.

Thanks!

+4
source share
1 answer

I believe that you need to make two modifications to jQuery Validate.

1.) Add a method to determine the first value of an empty string as an invalid value

  $.validator.addMethod( "SelectLetter", function(value, element) { if ($("#DropDown").val() === ''){ return false; } else return true; }, "Please Select a Letter" ); var validator = $("#LetterForm").validate({ rules: { DropDown: { SelectLetter: true } } }); 

2.) Add a click () event to validate

 $("#DropDown").click(function(){ $("#LetterForm").validate().element("#DropDown"); }); }); 

Full example http://jsfiddle.net/stupiddingo/L4c33/1/

There may be a simpler solution, but this seems to work. This is based on the answers to the question about the special jQuery validation method that was asked earlier.

0
source

All Articles