Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Last active November 15, 2018 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/f8d7237afa4e6b3e33a46ec42fb958f4 to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/f8d7237afa4e6b3e33a46ec42fb958f4 to your computer and use it in GitHub Desktop.
How to programmatically add an error message to the MVC ValidationSummary
// Set up an associative array for the error messages. The keys must be the exact name of the
// controls that need to have the error message displayed.
var errorArray = {
SomeProperty: "'SomeProperty' has shit the bed",
SomeOtherProperty: "Whoa - TWO errors? You are up the creek"
};
// Show the errors next to their associated controls
$('#form-to-validate').validate().showErrors(errorArray);
// Add the error messages to the validation summary.
// '[data-valmsg-summary]' is the name of the div that MVC injects into the markup; this shouldn't
// have to change when implementing this.
var validationSummary = $('[data-valmsg-summary]');
validationSummary.addClass('validation-summary-errors')
.removeClass('validation-summary-valid');
$.each(errorArray, function(index, item) {
// add each error
validationSummary.children('ul').append($('<li class="my-custom-error"></li>').text(item));
});
// OPTIONAL: Scroll to the top of the form to the top of the screen so the validation summary
// is visible.
$('#outlineContent').scrollTop(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment