Coming from the asp.net webforms model I’m used to using validators which display an error in the form <span title="Username is Required">*</span>.
I’m quite clear how the MVC3 validators work out of the box, so please no more answers explaining how validators work in MVC3 as I’m pretty sure I have that nailed. What I am trying to accomplish is have the validation error message showing as the title of the span tag as shown in the first paragraph.
I have managed to replicate this in MVC3 but am not sure if the way I have done it follows best practise. I would appreciate any input as to whether there is a better way to accomplish the same thing. It would be really great if it could be done without modifying jquery.validate.unobtrusive.js.
So what I have done is:
- Set the validation message to “*”
- Hidden the validation message while its valid
- Added a new attribute to determine whether to add the message as the title
- Added 2 lines of flagged code to onError to check whether to display the error message in the title, and if so to do so.
[.cshtml] @Html.ValidationMessageFor(m => m.Email, "*", new { data_val_usetitle = "true" })
[.css] .field-validation-valid {display:none;}
.js] function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false,
useTitle = $.parseJSON(container.attr("data-val-usetitle")) !== false; /* New Line */
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
if (useTitle) container.attr("title", error.text()); /* New Line */
error.hide();
}
}
I think what you’ve done is the cleanest way. There is no way around modifying jquery.validate.unobtrusive.js because MVC extensions don’t follow the old school asp.net methodology of emitting javascript on the fly.
I just finished creating my own custom validation extension calld ValidationIconFor() so that a single image is displayed with its title set to the error message and I’ve used a modified version of your code above.
jquery.validate.unobtrusive.js:
ValidationExtensions.cs: