Nick Olsen
Nick Olsen

Reputation: 6369

ASP.NET MVC Validation Using qTip jQuery Plugin

I am using the solution found here to show client side validation errors in a tooltip using the qTip jQuery plugin. This solution works great for client side validation but I would love to able to display server side validation errors in the same way. Does anyone know how to show server side validation errors in tooltips utilizing qTip?

Thanks

Upvotes: 8

Views: 3865

Answers (2)

tetius
tetius

Reputation: 465

The solution posted by Nick Olsen works great ! One observation :

The .replace() used in this statement only replaces the first occurrences of ‘.’ ‘[' and ']‘

var inputElem = ‘#’ + $(this).attr(‘data-valmsg-for’).replace(‘.’, ‘_’).replace(‘[', '_').replace(']‘, ‘_’);

To replace all occurrences the line should be something like :

var inputElem = "#" + $(this).attr("data-valmsg-for").replace(/\./g,"_").replace(/[\[\]]/g, "_");

Upvotes: 0

Nick Olsen
Nick Olsen

Reputation: 6369

If there is a server-side validation error, when the page loads there will be a span element with the class 'field-validation-error' so we can simply loop over all elements with that class, extract the content or the error message, and display it in a tooltip.

$(document).ready(function () {
    // Run this function for all validation error messages
    $('.field-validation-error').each(function () {

        // Get the name of the element the error message is intended for
        // Note: ASP.NET MVC replaces the '[', ']', and '.' characters with an
        // underscore but the data-valmsg-for value will have the original characters
        var inputElem = '#' + $(this).attr('data-valmsg-for').replace('.', '_').replace('[', '_').replace(']', '_');

        var corners = ['left center', 'right center'];
        var flipIt = $(inputElem).parents('span.right').length > 0;

        // Hide the default validation error
        $(this).addClass('Hidden');

        // Show the validation error using qTip
        $(inputElem).filter(':not(.valid)').qtip({                
            content: { text: $(this).text() } , // Set the content to be the error message
            position: {
                my: corners[flipIt ? 0 : 1],
                at: corners[flipIt ? 1 : 0],
                viewport: $(window)
            },
            show: { ready: true },
            hide: false,                
            style: { classes: 'ui-tooltip-red' }
        });            
    });
});

Here is a blog post that explains how to do this in detail.

Upvotes: 12

Related Questions