ASP.NET MVC验证使用qTip jQuery插件

时间:2011-08-10 20:04:06

标签: jquery asp.net-mvc asp.net-mvc-3 validation qtip

我正在使用找到的here解决方案,使用qTip jQuery插件在工具提示中显示客户端验证错误。此解决方案非常适合客户端验证,但我希望能够以相同的方式显示服务器端验证错误。有谁知道如何利用qTip在工具提示中显示服务器端验证错误?

由于

2 个答案:

答案 0 :(得分:12)

如果存在服务器端验证错误,当页面加载时会出现一个带有'field-validation-error'类的span元素,因此我们可以简单地循环遍历该类的所有元素,提取内容或者错误消息,并将其显示在工具提示中。

$(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' }
        });            
    });
});

以下是blog post,详细说明了如何执行此操作。

答案 1 :(得分:0)

Nick Olsen发布的解决方案效果很好! 一个观察结果:

此语句中使用的.replace()仅替换第一次出现的‘.’ ‘['']‘

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

要替换所有出现的行,应该是:

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