Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply Twitter Bootstrap Validation Style and Message to ASP.NET MVC validation

How can I integrate ASP.NET MVC unobtrusive validation and Twitter Bootstrap? I want to have all those validation messages and styles appropriately.

like image 573
SiberianGuy Avatar asked Jul 13 '12 09:07

SiberianGuy


9 Answers

A nice way of handling this if you're using Bootstrap 2 is...

Add this to your _Layout.cshtml:

<script type="text/javascript">

jQuery.validator.setDefaults({
    highlight: function (element, errorClass, validClass) {
        if (element.type === 'radio') {
            this.findByName(element.name).addClass(errorClass).removeClass(validClass);
        } else {
            $(element).addClass(errorClass).removeClass(validClass);
            $(element).closest('.control-group').removeClass('success').addClass('error');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        if (element.type === 'radio') {
            this.findByName(element.name).removeClass(errorClass).addClass(validClass);
        } else {
            $(element).removeClass(errorClass).addClass(validClass);
            $(element).closest('.control-group').removeClass('error').addClass('success');
        }
    }
});

$(function () {

    $("span.field-validation-valid, span.field-validation-error").addClass('help-inline');
    $("div.control-group").has("span.field-validation-error").addClass('error');
    $("div.validation-summary-errors").has("li:visible").addClass("alert alert-block alert-error");

});

</script>

These are the posts where I found the code pieces above:

Integrating Bootstrap Error styling with MVC’s Unobtrusive Error Validation

Twitter Bootstrap validation styles with ASP.NET MVC

MVC Twitter Bootstrap unobtrusive error handling


UPDATE

Right now I needed to do the same when using Bootstrap 3. Here's the modifications necessary since the class names changed:

<script type="text/javascript">

    jQuery.validator.setDefaults({
        highlight: function (element, errorClass, validClass)
        {
            if (element.type === 'radio')
            {
                this.findByName(element.name).addClass(errorClass).removeClass(validClass);
            } else
            {
                $(element).addClass(errorClass).removeClass(validClass);
                $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
            }
        },
        unhighlight: function (element, errorClass, validClass)
        {
            if (element.type === 'radio')
            {
                this.findByName(element.name).removeClass(errorClass).addClass(validClass);
            } else
            {
                $(element).removeClass(errorClass).addClass(validClass);
                $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
            }
        }
    });

$(function () {

    $("span.field-validation-valid, span.field-validation-error").addClass('help-block');
    $("div.form-group").has("span.field-validation-error").addClass('has-error');
    $("div.validation-summary-errors").has("li:visible").addClass("alert alert-block alert-danger");

});

</script>
like image 152
Leniel Maccaferri Avatar answered Sep 30 '22 07:09

Leniel Maccaferri


Copy the css of the validators in your css file and change the color accordinlgly. Something like this should do

.field-validation-error {
    color: #b94a48;
    display: inline-block;
    *display: inline;
    padding-left: 5px;
    vertical-align: middle;
    *zoom: 1;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    /*
    border: 1px solid #ff0000;
    background-color: #ffeeee;
    */
    color: #b94a48;
    border-color: #b94a48;
}

.input-validation-error:focus {
  border-color: #953b39;
  -webkit-box-shadow: 0 0 6px #d59392;
  -moz-box-shadow: 0 0 6px #d59392;
  box-shadow: 0 0 6px #d59392;
}

.validation-summary-errors {
    /*font-weight: bold;*/
    color: #b94a48;
}

.validation-summary-valid {
    display: none;
}
like image 30
Iridio Avatar answered Sep 30 '22 08:09

Iridio


I suggest to include Bootstrapper in less format and do the same thing as Iridio suggested but in .less. That way you could have something like:

.validation-summary-errors
{
    .alert();
    .alert-error();
}
.field-validation-error 
{
    .label();
    .label-important();
}

so when bootstrapper will change you'll pick up the changes automatically. Regular styles that handle visibility from MVC default Site.css will stay in place and handle visibility.

like image 31
Shaddix Avatar answered Sep 30 '22 06:09

Shaddix


Why not just use css !important and call it a day:

/* Styles for validation helpers
-----------------------------------------------------------*/
.field-validation-error {
    color: #f00 !important;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00 !important;
    background-color: #fee !important;
}

.validation-summary-errors {
    font-weight: bold;
    color: #f00;
}

.validation-summary-valid {
    display: none;
}
like image 25
Northstrider Avatar answered Sep 30 '22 07:09

Northstrider


On Bootstrap 3 you have to add:

.validation-summary-errors
{
    .alert();
    .alert-danger();
}
.field-validation-error 
{
    .label();
    .label-danger();
}

you'll see something like that:

Validation errors demo

like image 21
Roman Pushkin Avatar answered Sep 30 '22 07:09

Roman Pushkin


For the ValidationSummary, you can use the overload that allows you to specify htmlAttributes. This allows you to set it to use the Twitter Bootstrap alert css styles.

@Html.ValidationSummary(string.Empty, new { @class = "alert alert-danger" })

A similar overload exists for the ValidationMessage and ValidationMessageFor helper methods.

like image 25
Richard Ev Avatar answered Sep 30 '22 07:09

Richard Ev


You can integrate MVC3 validation with Bootstrap framework by adding the following javascript to your page (View)

<script>
$(document).ready(function () {
/* Bootstrap Fix */
$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest("div.control-group").addClass("error");
    },
    unhighlight: function (element) {
        $(element).closest("div.control-group").removeClass("error");
    }
});
var current_div;
$(".editor-label, .editor-field").each(function () {
    var $this = $(this);
    if ($this.hasClass("editor-label")) {
        current_div = $('<div class="control-group"></div>').insertBefore(this);
    }
    current_div.append(this);
});
$(".editor-label").each(function () {
    $(this).contents().unwrap();
});
$(".editor-field").each(function () {
    $(this).addClass("controls");
    $(this).removeClass("editor-field");
});
$("label").each(function () {
    $(this).addClass("control-label");
});
$("span.field-validation-valid, span.field-validation-error").each(function () {
    $(this).addClass("help-inline");
});
$("form").each(function () {
    $(this).addClass("form-horizontal");
    $(this).find("div.control-group").each(function () {
        if ($(this).find("span.field-validation-error").length > 0) {
            $(this).addClass("error");
        }
    });
});
});
</script>

Besides, on the Views (for example "Create.cshtml") make sure that the fields in the form are formatted as the following...

    <div class="editor-label">
        @Html.LabelFor(Function(model) model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(Function(model) model.Name)
        @Html.ValidationMessageFor(Function(model) model.Name)
    </div>
like image 35
Max Avatar answered Sep 30 '22 06:09

Max


For those using Bootstrap 3, the css classes have changed and the solutions above need modifications to work with Bootstrap 3. I have used the following with success with MVC 4 and Bootstrap 3. See this SO thread for more:

$(function () {
 // any validation summary items should be encapsulated by a class alert and alert-danger
    $('.validation-summary-errors').each(function () {
        $(this).addClass('alert');
        $(this).addClass('alert-danger');
    });

    // update validation fields on submission of form
    $('form').submit(function () {
        if ($(this).valid()) {
            $(this).find('div.control-group').each(function () {
                if ($(this).find('span.field-validation-error').length == 0) {
                    $(this).removeClass('has-error');
                    $(this).addClass('has-success');
                }
            });
        }
        else {
            $(this).find('div.control-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).removeClass('has-success');
                    $(this).addClass('has-error');
                }
            });
            $('.validation-summary-errors').each(function () {
                if ($(this).hasClass('alert-danger') == false) {
                    $(this).addClass('alert');
                    $(this).addClass('alert-danger');
                }
            });
        }
    });

    // check each form-group for errors on ready
    $('form').each(function () {
        $(this).find('div.form-group').each(function () {
            if ($(this).find('span.field-validation-error').length > 0) {
                $(this).addClass('has-error');
            }
        });
    });
});

var page = function () {
    //Update the validator
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest(".form-group").addClass("has-error");
            $(element).closest(".form-group").removeClass("has-success");
        },
        unhighlight: function (element) {
            $(element).closest(".form-group").removeClass("has-error");
            $(element).closest(".form-group").addClass("has-success");
        }
    });
}();
like image 20
Ben Ripley Avatar answered Sep 30 '22 06:09

Ben Ripley


You can add a few classes to your Site.css file:

/* styles for validation helpers */
.field-validation-error {
    color: #b94a48;
}

.field-validation-valid {
    display: none;
}

input.input-validation-error {
    border: 1px solid #b94a48;
}

select.input-validation-error {
    border: 1px solid #b94a48;
}

input[type="checkbox"].input-validation-error {
    border: 0 none;
}

.validation-summary-errors {
    color: #b94a48;
}

.validation-summary-valid {
    display: none;
}

FYI: http://weblogs.asp.net/jdanforth/form-validation-formatting-in-asp-net-mvc-5-and-bootstrap-3

like image 25
Darren Fang Avatar answered Sep 30 '22 07:09

Darren Fang