Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.