将BootstrapValidator与MVC DataAnnotations一起使用

Dot*_*ude 16 validation asp.net-mvc data-annotations asp.net-mvc-4 twitter-bootstrap

DataAnnotations用来指定我的验证规则,默认情况下,这些验证规则在客户端添加,以供jquery验证.

我想使用BootstrapValidator.js,因为我喜欢呈现错误/成功消息的方式.但是,它要求我在客户端重新定义验证规则.可以找到一篇关于BootstrapValidator.js的文章.

有没有办法DataAnnotations在一个地方使用和定义规则,仍然使用BootstrapValidator?

有什么想法吗?

Ami*_*rzi 4

无需再次重新定义验证规则。您可以简单地将MVC 类型验证(即Jquery Validation Plugin)与 Bootstrap 样式集成,方法是删除快速脚本并在 MVC 验证脚本之后引用它:

$(function () {
    $('span.field-validation-valid, span.field-validation-error').each(function () {
        $(this).addClass('help-inline');
    });

    $('.validation-summary-errors').each(function () {
        $(this).addClass('alert');
        $(this).addClass('alert-error');
        $(this).addClass('alert-block');
    });

    $('form').submit(function () {
        if ($(this).valid()) {
            $(this).find('div.control-group').each(function () {
                if ($(this).find('span.field-validation-error').length == 0) {
                    $(this).removeClass('error');
                }
            });
        }
        else {
            $(this).find('div.control-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).addClass('error');
                }
            });
            $('.validation-summary-errors').each(function () {
                if ($(this).hasClass('alert-error') == false) {
                    $(this).addClass('alert');
                    $(this).addClass('alert-error');
                    $(this).addClass('alert-block');
                }
            });
        }
    });

    $('form').each(function () {
        $(this).find('div.control-group').each(function () {
            if ($(this).find('span.field-validation-error').length > 0) {
                $(this).addClass('error');
            }
        });
    });

    $("input[type='password'], input[type='text']").blur(function () {
        if ($(this).hasClass('input-validation-error') == true || $(this).closest(".control-group").find('span.field-validation-error').length > 0) {
            $(this).addClass('error');
            $(this).closest(".control-group").addClass("error");
        } else {
            $(this).removeClass('error');
            $(this).closest(".control-group").removeClass("error");
        }
    });
});

var page = function () {
    //Update that validator
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest(".control-group").addClass("error");
        },
        unhighlight: function (element) {
            $(element).closest(".control-group").removeClass("error");
        }
    });
} ();
Run Code Online (Sandbox Code Playgroud)