This is often used in conjunction with a validation summary, which contains all the descriptive text, and then the various fields on the form are marked invalid with a small error icon for added visibility. Such a thing is easy to do with ASP.NET webforms validators, allowing you to specify whatever markup you wish in the validation message. But in MVC the client-side behaviour is locked away in the javascript validation libraries. ValidationExtensions can allow you to create different types of validators, and even manipulate the validator container (a span), but you are still subject to client-side behaviour where a second span, containing the validation message, is dynamically generated and set inside the validator container span.
Fortunately, if you are using the MicrosoftMvcJQueryValidation javascript library, a two line change can modify this behaviour. Search for the code snippet below (expanded from MicrosoftMvcJQueryValidation.min.js) and add the lines in bold:
errorPlacement: function (error, element) {
var messageSpan = fieldToMessageMappings[element.attr
("name")];
$(messageSpan).empty();
$(messageSpan).removeClass("field-validation-valid");
$(messageSpan).addClass("field-validation-error");
error.removeClass("input-validation-error");
error.attr("_for_validation_message", messageSpan);//Change - replace span contents with error icon and
alternate text
var errorMessage = error.html();
error.html('<img src="/Images/Icons/Error.gif"
alt="' + errorMessage + '"
title="' + errorMessage + '"
width="16"
height="16" />'
);
error.appendTo(messageSpan);
},
This replaces the span's text contents with an error icon of your choice with appropriate alternate text.
I hope this code helps, I'll be pursuing the MVC team to bake this functionality into the framework so it can be easily configured, as of MVC 3 it doesn't appear to be implemented.
1 comment:
I have posted a blog post here that explains how to go about doing this from beginning to end for both client and server side validation. It uses a little bit different approach.
Post a Comment