ASP.NET MVC Validation Using qTip jQuery Plugin
Asked Answered
O

2

8

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

Orel answered 10/8, 2011 at 20:4 Comment(0)
O
12

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.

Orel answered 11/8, 2011 at 14:59 Comment(0)
W
0

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, "_");
Warmblooded answered 31/10, 2012 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.