Cranking Code

Mark Holland

Styling asp.net MVC Validation Summary as a Twitter Bootstrap Flash

The asp.net MVC validation summary is a bit plain. Let’s beautify it.

First grab the alert styles from the Twitter Bootstrap source and add the ‘.validation-summary-errors’ class selector where appropriate. I’ve used the “danger” (red) version of the flash.

1
2
3
4
5
6
7
8
9
10
   .validation-summary-errors,
  .alert-message
  {
     clear:both;
    position: relative;
    padding: 7px 15px;
    margin-bottom: 18px;
    color: #404040;
  
  etc...   

Just that alone will make things look miles better already.

However the Bootstrap flash has a close button on it in order to hide the message away which is kind of neat. Let’s use JavaScript to add that.

First we need to know if flash is present. If a full page postback has triggered the showing of the validation error message then we can just look for it in the DOM on document ready.

1
2
3
4
5
   var $validationSummaryErrors = $('.validation-summary-errors');
  
  if ($validationSummaryErrors.length !== 0) {
      addCloseButton($validationSummaryErrors);
  }

Simple.

But what if the validation error message was injected via client side code?

jquery.validate.unobtrusive.js, the Javascript code which performs client side model validation, runs on page load and has no input parameters so we can’t pass in a callback directly. Instead, I’m afraid, we need to add a function to the global object.

1
2
3
   window.onValidatorSummaryShown = function () {
      addCloseButton(this);
  };

And we’ll call it when the ‘.validation-summary-errors’ div is injected into the DOM.

1
2
3
    if (window.onValidatorSummaryShown) {
                window.onValidatorSummaryShown.call(container);
     }

And there you have it, a beautiful and arresting validation error message complete with working close button.

The code in full: