ASP.NET MVC Validation Using qTip jQuery Plugin

前端 未结 2 900
有刺的猬
有刺的猬 2021-02-03 12:54

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 w

相关标签:
2条回答
  • 2021-02-03 13:40

    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, "_");
    
    0 讨论(0)
  • 2021-02-03 13:43

    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.

    0 讨论(0)
提交回复
热议问题