The setup:
The 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 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 issue:
It seems that the events don't kick in for the mouse events until validation is triggered for the first time (either by changing the values with the keyboard or pressing the submit button). Any explanations as to why this is happening (am I doing something wrong?), or workarounds, would be greatly appreciated.
Thanks!
I believe you need to make two modifications to JQuery Validate.
1.) Add a method to define the first value of empty string as not a valid 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 fire validation
$("#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 off the answers to jQuery custom validation method issue asked previously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With