Last active
November 15, 2018 16:33
-
-
Save jeffjohnson9046/f8d7237afa4e6b3e33a46ec42fb958f4 to your computer and use it in GitHub Desktop.
How to programmatically add an error message to the MVC ValidationSummary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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